Batch file - ping loop - output to host files that are up

I would like to create a .bat file that will execute a for loop, as shown below:

@echo off FOR /L %%G IN (1, 1, 69) DO ( ping -n 1 192.168.%%G.3 ping -n 1 192.168.%%G.4 ) 

Then view the output and send only the IP addresses that successfully answered ping to the txt file. Is this possible with a CMD batch file?

+4
source share
2 answers
 @ECHO OFF SET output=%USERPROFILE%\output.txt IF EXIST "%output%" DEL "%output%" FOR /L %%G IN (1, 1, 69) DO ( CALL :ping 192.168.%%G.3 CALL :ping 192.168.%%G.4 ) GOTO :EOF :ping ping -n 1 %1 >NUL && ECHO %1>>"%output%" 

Basically, you use && to add a command that only runs if the previous command (the first before && ) completed successfully (technically speaking, returned exit code 0 ).

There is a similar approach for the opposite case. If you want to perform some actions on the unsuccessful result of the command, you put || after it, and then the team that implements your action.

EDIT

One note on ping . Sometimes you get a notification from the router that the host is unreachable. In this case, ping still exits with code 0 ("successful"), because it receives a response, even if it is from the router and not from the actual host.

If this can happen to your hosts, and you do not want to have such false positives in the output file, you will have to analyze the ping output for some keywords indicating whether pinging was successful, while you can rely on lines showing aggregate statistics: they appear only if the response was from the intended host.

So here is an alternative approach:

 @ECHO OFF SET output=%USERPROFILE%\output.txt IF EXIST "%output%" DEL "%output%" FOR /L %%G IN (1, 1, 69) DO ( CALL :ping 192.168.%%G.3 CALL :ping 192.168.%%G.4 ) GOTO :EOF :ping ping -n 1 %1 | find "Approximate round trip" >NUL && ECHO %1>>"%output%" 

EDIT 2

Both solutions have been changed for using a subroutine call to avoid premature expansion of %ip% inside a for loop. (It can also be fixed by enabling slow expansion.)

Also cited is %output% everywhere.

+6
source
 @echo off :A FOR /L %%G IN (1, 1, 69) DO ( ping -n 1 192.168.%%G.3 ping -n 1 192.168.%%G.4 ) :GoTo 
-1
source

Source: https://habr.com/ru/post/1340264/


All Articles