Grab IP addresses only by pinging list of server names using Batch

4.4k views Asked by At

I have a text file containing a list of a few hundred server names

Server1

Server2

Server3

Server4

and so on...

I want to run a batch file which will take this file , ping all of them and return just the IP address if found, or "DOWN" if unreachable or not found. I want the output to go into output.txt, and the output only needs to be the IP address or "DOWN".

Sample output:

176.28.29.100

DOWN

176.28.29.105

176.28.29.110

Edit: I am new to batch and so far I have done this: Throw servernames into excel, get this in another column for the number of servernames

ping -n 1 servername | findstr "Pinging host" >> out.txt

...

The output I get is in the form

Ping request could not find host Server1. Please check the name and try again.

Pinging Sever2 [176.28.29.105] with 32 bytes of data:

Reply from 176.28.29.110: Destination host unreachable.

Want to get just the IPs

2

There are 2 answers

0
Stephan On BEST ANSWER

to process a file line by line, use for /f:

@echo off
setlocal enabledelayedexpansion

for /f %%i in (servers.txt) do (
  set p=DOWN
  set r=no response
  for /f "tokens=2 delims=[]" %%p in ('ping -n 1 -w 1 %%i^|find "["' ) do set p=%%p
  ping -n 1 -w 2000 %%i|find "TTL" >nul && set r=running
  echo %%i  is !p! !r!
)

(adapt the echo line to your needs)

1
SachaDee On

You can try like this :

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in (server.txt) do (
  set "$ip="
  for /f "delims=[] tokens=2" %%b in ('ping -n 1 %%a ^| find "["') do (
   set "$ip=%%b"
  )
   if defined $ip (echo %%a - !$ip! OK) else (echo %%a KO) 
)