How to ping multiple servers and return IP address and Hostnames using batch script?

后端 未结 8 1671
余生分开走
余生分开走 2020-12-28 10:45

So I have to use batch only for this. Basically, the server HOSTNAMES are all listed in a txt file. I used the following code to ping all the servers and di

8条回答
  •  时光说笑
    2020-12-28 11:21

    the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.

    better do it this way

    ping -n 4 %1 | findstr TTL
    if %errorlevel%==0 (goto :eof) else (goto :error)
    

    this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping

    overall this looks like this:

    @echo off
    SetLocal
    
    
    set log=path/to/logfile.txt
    set check=path/to/checkfile.txt
    
    :start
    echo. some echo date >>%log%
    
    :check
    for /f %%r in (%check%) do (call :ping %%r)
    goto :eof
    
    :ping
    ping -n 4 %1 | findstr TTL
    if %errorlevel%==0 (goto :eof) else (goto :error)
    
    :error
    echo. some errormessage to >>%log%
    echo. some blat to mail?
    
    :eof
    echo. some good message to >>%log%
    

提交回复
热议问题