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

后端 未结 8 1727
余生分开走
余生分开走 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:29

    Well, it's unfortunate that you didn't post your own code too, so that it could be corrected.
    Anyway, here's my own solution to this:

    @echo off
    setlocal enabledelayedexpansion
    
    set OUTPUT_FILE=result.txt
    >nul copy nul %OUTPUT_FILE%
    for /f %%i in (testservers.txt) do (
        set SERVER_ADDRESS=ADDRESS N/A
        for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
            if %%x==Pinging set SERVER_ADDRESS=%%y
            if %%x==Reply set SERVER_ADDRESS=%%z
            if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
        )
        echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
    )
    

    The outer loop iterates through the hosts and the inner loop parses the ping output. The first two if statements handle the two possible cases of IP address resolution:

    1. The host name is the host IP address.
    2. The host IP address can be resolved from its name.

    If the host IP address cannot be resolved, the address is set to "ADDRESS N/A".

    Hope this helps.

提交回复
热议问题