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

雨燕双飞 提交于 2019-12-23 04:51:37

问题


Working 1 loop code:

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

Not running code where I try to use a counter so every time the ping gets a reply we add 1 to online:

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

Thanks a lot.


回答1:


Reply from 146.57.239.18: Destination host unreachable 

The destination is not reachable, so your local host (146.57.239.18) replies with "Destination host unreachable").

146.57.239.18 is not the pinged host, but your localhost.

It's better to search for TTL= instead of Reply:

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

Also your set /a online=%online%+1 doesn't work. You would need delayed expansion. The set /a online +=1 syntax works better:

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

As a result, the whole code would look like:

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 a much quicker solution (working parallel):

@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



回答2:


You have the syntax slightly wrong. The following should work (split over a couple of lines for readability:

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"
  )
)

Keep in mind that this is a lot of IPs to ping.



来源:https://stackoverflow.com/questions/32813983/batch-script-with-nested-loops-to-ping-range-of-ips

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