【问题标题】:Pinging to multiple servers via windows batch script通过 Windows 批处理脚本 ping 到多个服务器
【发布时间】:2018-12-24 19:37:08
【问题描述】:

我正在尝试通过 windows 批处理脚本 使用 ping 命令检查 n 千个 IP 列表中的响应,并将所有结果保存在一个文件中( 如果响应,no 如果不响应)。这甚至可以通过批处理脚本实现吗?当我使用下面打印的脚本 (pingingN.bat) 时,我只会得到第一个 IP 答案。

@ECHO OFF

SET ServerList="C:\MyPath\ip.txt"
SET LogFile="C:\MyPath\PingResults.txt"

IF EXISTS %LogFile% DEL %LogFile%

FOR %%a IN (%ServerList%) DO (
    ping -n 1 %%a | find "TTL=" > NUL
    IF %ERRORLEVEL% NEQ 0 (
        echo no >> %LogFile%
    ) ELSE (
        echo yes >> %LogFile%
    )
)

【问题讨论】:

  • 回答您的问题:是的,有可能。无论如何,在您的代码中,您需要 delayed expansion 用于 ErrorLevel,以便 %ErrorLevel% 变为 !ErrorLevel!,或者您将 if %ErrorLevel% neq 0 更改为 if ErrorLevel 1(意思是 如果 ErrorLevel 等于或大于 1),因为ping 无论如何都不会返回否定的ErrorLevel...
  • 另外SET ServerList="C:\MyPath\ip.txt"应该是SET "ServerList=C:\MyPath\ip.txt"SET LogFile="C:\MyPath\PingResults.txt"应该是SET "LogFile=C:\MyPath\PingResults.txt"IF EXISTS %LogFile% DEL %LogFile%应该是IF EXIST "%LogFile%" DEL "%LogFile%"FOR %%a IN (%ServerList%) DO (应该是FOR /F UseBackQ %%a IN ("%ServerList%") DO (

标签: windows shell batch-file cmd scripting


【解决方案1】:
  1. 创建一个文件 (test.txt) 并列出您要 ping 的所有 IP。
  2. 创建另一个 bat.file 并编写此命令。

(for /F %i in (test.txt) do ping -n 1 %i 1>nul && echo %i UP || echo %i DOWN ) 1>result.txt

  1. 运行此命令,它会列出哪些 IP 已启动,哪些 IP 已关闭。

【讨论】:

    【解决方案2】:

    根据我的评论并使用&&|| 条件,我会这样做:

    @Echo Off
    
    Set "ServerList=C:\MyPath\ip.txt"
    Set "LogFile=C:\MyPath\PingResults.txt"
    
    If Not Exist "%ServerList%" Exit /B
    >"%LogFile%" (For /F UseBackQ %%A In ("%ServerList%"
    ) Do Ping -n 1 %%A|Find "TTL=">Nul&&(Echo Yes [%%A])||Echo No [%%A])
    

    您会注意到我还在输出中包含了 IP,否则您的日志文件将不会显示哪些通过/未通过/失败。

    【讨论】:

      【解决方案3】:

      您可以使用delayed Expansionif errorlevel(由 aschipfl 评论)或使用其他方法:

      (FOR %%a IN (%ServerList%) DO (
         ping -n 1 %%a | find "TTL=" > NUL && (
            echo %%a, yes
         ) || (
            echo %%a, no
         )
      )>%LogFile%
      

      其中&& 表示“如果上一个命令 (find) 成功则”,||“如果上一个命令 (find) 失败则”

      只需将整个输出重定向一次,而不是单独重定向每一行,即可大大提高速度。

      【讨论】: