Grepping a batch ping

99封情书 提交于 2019-12-10 23:58:20

问题


Looking for a better way to do this rather than the "by-hand" method I'm used to, because it's a process I have to go through fairly regularly.

I have a range of IPs to ping, from 10.0.1.15 to 10.0.50.15. The third octet refers to a physical location and the last octet refers to a device at that location. I need to see which locations DO NOT have that device hooked up to the network.

My current solution is:

FOR /L %i IN (1,1,50) DO ping -n 1 10.0.%i.15 >> C:\path\to\output\file.txt

This gives me output like

Pinging 10.0.1.15 with 32 bytes of data:
Reply from 10.0.1.15: bytes=32 time=68ms TTL=255

Ping statistics for 10.0.1.15:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 68ms, Maximum = 68ms, Average = 68ms

Pinging 10.0.2.15 with 32 bytes of data:
Request timed out.

Ping statistics for 10.0.2.15:
    Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
...

I'd prefer output more like:

2
...

But honestly anything human-readable is fine -- this isn't being piped anywhere.

In this case, location 1 has the device present, but location 2 does not.

Currently the best solution I have for doing this is to look through that file by hand and keep track. I could hack something together in Python but it sounds like more trouble than it's worth. I know that grep has some ability to show context, but I'm on Windows and don't have access to anything but the basic NT CLI tools.

Is there some way to leverage findstr (or etc) to get a more easily human-readable output? Is there some better method in e.g. Powershell?


回答1:


Sure. You can use find (or findstr if you prefer) to test for the existence of "TTL" "TTL=" (edit: See MC ND's comment below) and use the resulting ERRORLEVEL to determine success or fail.

@echo off
setlocal

for /L %%I in (1,1,50) do (
    ping -n 1 10.0.%%I.15 | find /i "TTL=" >NUL && (
        echo 10.0.%%I.15: Online
    ) || (
        echo 10.0.%%I.15: OFFLINE
    )
)

See this page for more info on conditional execution (the && and || stuff). find sets ERRORLEVEL to 0 on success, or 1 on fail. If you want the results logged to a txt file rather than the console, just wrap the whole thing in another parenthetical code block like this:

@echo off
setlocal

set "logfile=C:\path\to\output\file.txt"

>> "%logfile%" (
    for /L %%I in (1,1,50) do (
        ping -n 1 10.0.%%I.15 | find /i "TTL=" >NUL && (
            echo 10.0.%%I.15: Online
        ) || (
            echo 10.0.%%I.15: OFFLINE
        )
    )
)

type "%logfile%"


来源:https://stackoverflow.com/questions/27787016/grepping-a-batch-ping

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