批处理 - 脚本ping多个ip

时间:2013-10-27 17:38:36

标签: batch-file ping

我想创建一个脚本来ping许多IP地址。但我不想使用errorlevel。

我想ping每个IP地址5次,并显示结果:

  • 如果丢失5个数据包,我想显示echo%ip - DOWN
  • 如果丢失了3个数据包,我想显示一个echo%ip - 3 lost
  • 等...

所以我想从这一行的变量中找回“丢失的数据包”:

“数据包:已发送= 4,已收到= 4,已丢失= 0 (0%已丢失)

这是我的代码,但这不起作用。

echo off 

set perte=0 
set servers=servers.txt 

for /f %%i in (%servers%) do call :testping %%i 
goto:eof

:testping 
FOR /f "tokens=3 delims==" %%a IN (' ping -n 5 %1 ^|find "lost"') 
DO (set perte=%%b) 

if %perte%==1 echo %1 lost 1 ping
if %perte%==2 echo %1 lost 2 ping
if %perte%==3 echo %1 lost 3 ping
if %perte%==4 echo %1 lost 4 ping
if %perte%==5 echo %1 DOWN
if %perte%==0 echo %1 UP
goto:eof

2 个答案:

答案 0 :(得分:1)

更改了令牌,delims和find命令。

@echo off 

set perte=0 
set servers=servers.txt 

for /f %%i in (%servers%) do call :testping %%i 
goto:eof

:testping 
FOR /f "tokens=7 delims== " %%a IN (' ping -n 5 %1 ^|find /i "lost"') DO (set perte=%%a) 

if %perte%==1 echo %1 lost 1 ping
if %perte%==2 echo %1 lost 2 ping
if %perte%==3 echo %1 lost 3 ping
if %perte%==4 echo %1 lost 4 ping
if %perte%==5 echo %1 DOWN
if %perte%==0 echo %1 UP
goto:eof

答案 1 :(得分:0)

几乎完成了。尝试

@echo off 

    setlocal enableextensions 

    set servers=servers.txt

    for /f %%i in (%servers%) do call :testping %%i

    endlocal
    exit /b

:testping 
    rem
    rem How/Why delims are defined as =,(
    rem Packets: Sent = 5, Received = 5, Lost = 0 (0% loss), 
    rem ..............^..^..........^..^......^...^.........
    rem token: 1       2  3          4  5      6   7
    rem
    FOR /f "tokens=6 delims==,(" %%a IN (' ping -n 5 %1 ^| find /i "lost" ') do (
        if %%a EQU 0 (
            echo %1 UP
        ) else if %%a EQU 5 (
            echo %1 DOWN
        ) else (
            echo %1 lost %%a ping
        )
    )
    goto :EOF