Batch ping a list of computer names and write the results to file

假装没事ソ 提交于 2019-12-11 04:38:42

问题


The code below will write the computer name and ip address to file, but I would like it to also write the name of the computers it cannot ping with a fail next to it. I have no idea how I would modify the batch file to do this.

@echo off

Echo Pinging list...

set ComputerList=list.txt

Echo Computername,IP Address>Final.csv
setlocal enabledelayedexpansion

for /f "usebackq tokens=*" %%A in ("%ComputerList%") do (
for /f "tokens=3" %%B in ('ping -n 1 -l 1 %%A ^|findstr Reply') do (
set IPadd=%%B
echo %%A,!IPadd:~0, -1!>>Results.csv
))

pause

回答1:


You could use errorlevel set by findstr to substitute return string(s) if 'Reply' is not found:

('ping -n 1 -l 1 %%A ^|findstr Reply ^|^| echo Not found Failed:')  

where || (escaped here because of for context with ^) means execute only if previous command failed.

As a side note, you should be aware that ping messages are system language dependent (they are translated to language of OS) so 'Reply' as success indicator works only for English versions.




回答2:


This may not be directly what you are looking for, but I had a similar task: run ping and report success or failure. I'll leave extracting the IP address to you - seeing as you have already done it.

The problem with ping is that it returns success upon name resolution, whether packets get lost or host is unreachable (will report 0% Loss) is irrelevant.

FOR %%a IN (
 google.com
 a.b.c.d
) DO @FOR /F "delims=" %%p IN (
     'PING -w 100 -n 1 %%a ^| findstr ^"Reply Request fail name^"'
   ) DO @(
     ECHO "%%p" | FINDSTR TTL >2 && echo %%a, success, %%p || echo %%a, failed, %%p
   ) >> Results.csv

Logic: Ping once, filter only lines with the one of the words listed. If TTL exists in resulting line (output to STDERR or NUL to avoid output pollution) echo success, else echo failed.

I'm on English Windows, words will have to be adjusted for other languages.

EDIT:

FOR %%a IN (
 google.com
 a.b.c.d
) DO @FOR /F "delims=" %%p IN ('PING -n 1 %%a ^| findstr TTL ^|^| echo Failed') DO @(
       ECHO "%%p" | FINDSTR TTL >2 && (for /f "tokens=3" %%b IN ("%%p") do @echo %%a, %%b) || echo %%a, failed, %%p
     )

Less dependant on language, works only for IPv4, added IP extraction. Filter ping output for TTL, set output to "Failed" if TTL not found. If output string contains TTL, extract IP and echo host and IP, else echo host name and output string.



来源:https://stackoverflow.com/questions/13831218/batch-ping-a-list-of-computer-names-and-write-the-results-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!