简体   繁体   中英

Adding names to an IP address without failing the batch file

I want to use a batch file to ping a set of servers. The batch file works and reports ok or failed. All I want is to have it display a name of the server in the check.

This is what I use in the batch file:

@echo off
for /f "delims=" %%a in (C:\List of IPs.txt) do ping -n 1 %%a >nul && (echo %%a ok) || (echo %%a failed to respond) 
pause

In the text file it points to is just a list of IPs, how do I make it so I can see a name next to the IP? Thank you in advance!

just insert another for /f loop to get the name:

@echo off
SetLocal 
for /f "usebackq" %%a in ("List of IPs.txt") do (
  for /f %%b in ('"ping -n 1 %%a >nul && (echo ok) || (echo failed to respond) "') do (
    for /f "tokens=1*" %%m in ('nslookup %%a  ^|findstr /b "Name:"') do (
     echo %%a   %%n %%b
    )
  )
)

One option is to format your file to have the IP and the name you are interested in.

192.168.1.200 server1
192.168.1.201 server2
192.168.1.202 printer1
192.168.1.203 that one stupid printer in the back

Then you can read both from the file. One thing I'll note -- your method of checking pings is not consistent. You can get an errorlevel 0 even if the ping actually fails (from a valid response of "unreachable"). Instead (in English) a successful ping always includes "ttl=". Thus you would do this:

untested

@echo off
for /f "usebackq tokens=1* delims= " %%a in ("C:\List of IPs.txt") do ping -n 1 %%a ^|find /i "ttl=" >nul && (echo %%b at %%a is ok) || (echo %%b at %%a failed to respond)
pause

nslookup and/or ping -a can be leveraged if you have dns working with everything you're trying to access.

Based on comment, I've added the following solution that works on my English Windows 10 computer with the text file above:

@echo off
for /f "usebackq tokens=1* delims= " %%a in ("C:\temp\List of IPs.txt") do ping -n 1 -w 1500 %%a |find /i "ttl=" >nul &&echo %%b at %%a is ok||echo %%b at %%a failed to respond
pause

Note there is a space between the equal sign and the double quote at delims= "

Output:

server1 at 192.168.1.200 is ok
server2 at 192.168.1.201 is ok
printer1 at 192.168.1.202 is ok
that one stupid printer in the back at 192.168.1.203 failed to respond
Press any key to continue . . .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM