无法获取批处理脚本以将IP地址,Ping状态和主机名显示为单个3列.csv

时间:2015-07-20 20:00:06

标签: batch-file

我正在尝试对网站列表进行ping操作,并在.csv,主机名,ping成功,IP地址中获得以下输出。所以输出可能如下所示:

Google.com,成功(或失败),123.456.789.012(如果失败N / A)

我有两个脚本可以做这些事情seperatley,但似乎无法让他们一起工作。

获取IP地址:

@echo off
set ComputerList=C:\Scripts\pinglist.txt
Echo Computername,IP Address>>pingresult.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!>>pingresult.csv
))*

获取主机名和ping状态:

REM Set the "PingList" variable to the location of the text file you want to ping against
set PingList=C:\Scripts\pinglist.txt
REM Set the "Results" variable to the location where you want to pipe your output
set Results=C:\Scripts\pingresult.csv
echo COMPUTERNAME, STATUS >> %Results%
REM failed pings appened to file
for /f "delims=" %%a in (%PingList%) do ping -n 1 %%a >nul && (echo %%a ok) || (echo %%a, failure ) >> %Results%
REM successful pings appened to file
for /f "delims=" %%a in (%PingList%) do ping -n 1 %%a >nul && (echo %%a, success ) >> %Results% || (echo %%a failed to respond)

1 个答案:

答案 0 :(得分:0)

改革another answer;没有优化:

@ECHO OFF >NUL
@SETLOCAL enableextensions
echo COMPUTERNAME, STATUS, IP
for /F "usebackq delims=" %%i in ("files\30852528.txt") do (
  set "_found="
  for /F "delims=" %%G in ('
      ping -4 -n 1 %%i^|findstr /i /C:"Ping request could not find host"') do (
    echo %%i, "Could not find host", "" 
    set "_found=%%G"
  )
  if not defined _found (
    for /F "tokens=3 delims=: " %%G in ('
        ping -4 -n 1 %%i^|findstr /i "TTL="') do (
      echo %%i, "ok", %%G 
      set "_found=%%G"
    )
  )
  if not defined _found (
    for /F "tokens=2 delims=[]" %%G in ('
        ping -4 -n 1 %%i^|findstr /ib "Pinging"') do (
      echo %%i, "Request timed out", %%G 
      set "_found=%%G"
    )
  ) 
  if not defined _found (
      echo unknown ? %%i
  )
) 

<强>输出

==>D:\bat\SO\31525308.bat
COMPUTERNAME, STATUS, IP
foo.bar, "Could not find host", ""
google.com, "ok", 173.194.112.100
yahoo.com, "ok", 98.139.183.24
toyota.com, "ok", 95.101.1.91
bmw.com, "Request timed out", 160.46.244.131

==>