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

后端 未结 2 2005
猫巷女王i
猫巷女王i 2021-01-13 20:21

I would like to make a .bat file 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.1         


        
相关标签:
2条回答
  • 2021-01-13 20:43
    @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 讨论(0)
  • 2021-01-13 20:46
    @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.

    0 讨论(0)
提交回复
热议问题