开发者

Batch file - loop ping - output to file hosts that are up

开发者 https://www.devze.com 2023-02-12 00:33 出处:网络
I would like to make a .bat f开发者_JAVA百科ile that will do a for loop like below: @echo off FOR /L %%G IN (1, 1, 69) DO (

I would like to make a .bat f开发者_JAVA百科ile that will do a for loop like 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 look through the output and send only the IPs that replied successfully to the ping to a txt file. Is this possible with a CMD batch file?


@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 the command that is only executed if the previous command (the one before the &&) completed successfully (technically speaking, returned the exit code of 0).

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

EDIT

One note about ping. Sometimes you get a notification from the router that the host is not accessible. In this case ping still exits with 0 code ('successful'), because it does get a reply, even if it's from the router and not from the actual host.

If that can be the case with your hosts and you don't want to have such false positives in the output file, you'll have to parse the output of ping for some keywords indicating whether the pinging was successful indeed. So far you can rely on the lines showing the aggregate stats: they only appear if the reply was from the intended host.

So, here's the 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

Changed both solutions to use subroutine call in order to avoid premature expansion of %ip% inside the for loop. (Could also be fixed by enabling delayed expansion instead.)

Also quoted %output% everywhere.


@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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号