具有嵌套循环的批处理脚本,用于 ping IP 范围

Batch script with nested loops to ping range of IP's

工作 1 循环代码:

for /l %i in (1,1,254) do @ping 131.212.30.%i -n 1 -w 100 | find "Reply"

不是 运行 我尝试使用计数器的代码,因此每次 ping 收到回复时我们都会在线加 1:

SET online=0 for /L %i in (1,1,254) do for /L %j in (1,1,255) do @ping 131.212.%i.%j -n 1 -w 100 | find "Reply" SET /A online=online+1

非常感谢。

你的语法有点错误。以下内容应该有效(为了便于阅读,分成几行:

for /l %%i in (1,1,254) do (
  for /l %%j in (1,1,254) do (
    ping 131.212.%%i.%%j -n 1 -w 100 | find "Reply"
  )
)

请记住,要 ping 的 IP 很多。

Reply from 146.57.239.18: Destination host unreachable 

无法到达目的地,因此您的本地主机 (146.57.239.18) 回复 "Destination host unreachable")。

146.57.239.18 不是被 ping 的主机,而是您的本地主机。

最好搜索 TTL= 而不是 Reply:

...
ping 131.212.%%i.%%j -n 1 -w 100 | find "TTL="
...

您的 set /a online=%online%+1 也不起作用。你需要 set /a online +=1 语法效果更好:

...
ping 131.212.%%i.%%j -n 1 -w 100 | find "TTL=" && SET /A online +=1 || set /a offline +=1
...

因此,整个代码如下所示:

SET online=0 
for /L %%i in (1,1,254) do for /L %%j in (1,1,255) do ping 131.212.%%i.%%j -n 1 -w 100 | find "TTL=" && SET /A online +=1 
echo %online% hosts are online.

EDIT 一个更快的解决方案(并行工作):

@echo off 
SET online=0 
for /L %%i in (1,1,254) do (
  start /min "pinging" cmd /c "(@for /L %%j in (1,1,255) do @ping 146.254.%%i.%%j -n 1 -w 100 | find "TTL=") >ping%%i.txt"
)

:loop
timeout /t 1 >nul
tasklist /v | find "pinging" && goto :loop
pause

for /f %%i in ('type ping*.txt 2^>nul^|find /c "TTL="') do echo %%i hosts are online
del ping*.txt