【问题标题】:How to record ping statistics in tabular format?如何以表格格式记录 ping 统计信息?
【发布时间】:2015-07-21 19:10:05
【问题描述】:

我需要在 windows 上将 ping 统计信息记录为表格格式。

C:\Users\hsangal>ping localhost -t -n 2

Pinging TechBeamers.local [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

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

我想使用 Windows 批处理脚本来执行此操作,并寻求专家的指导。我希望以表格格式记录的数据是下面突出显示的 ping 命令输出的一部分:

Packets: Sent = 2, Received = 2, Lost = 0 (0% loss)

【问题讨论】:

    标签: windows batch-file scripting


    【解决方案1】:

    您可以使用find 获取仅包含感兴趣信息的行,例如:

    ping localhost -n 2 | find "Packets:"
    

    这只会返回Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),这一行。
    然后你像这样环绕for /F 语句:

    for /F "tokens=3,5,7,8 delims=,=() " %I in ('ping localhost -n 2 ^| find "Packets:"') do echo %I;%J;%K;%L
    

    然后输出将是这样的(发送的数据包;接收的数据包;丢失的数据包;丢失百分比):

    2;2;0;0%
    

    当然,您可以指定 (a) 除 ; 以外的分隔符(只需在最后的 echo 语句中交换)。
    请注意,上述代码仅在直接输入命令提示符时才有效。如果您想在批处理文件中使用它,请将变量 %I 等替换为 %%I

    注意:当您提供 -n 开关时,ping 命令行中的 -t 开关将被忽略。

    【讨论】:

      【解决方案2】:

      如果您要编写脚本并希望格式化输出,您可能需要考虑 Powershell Test-Connection。它有更多的选项来格式化输出。

      多个输出例如: c:> 测试连接 www.google.co.za, www.yahoo.com

      列选择和导出只是其中的一些功能。此链接提供了一个很好的概述:https://technet.microsoft.com/en-us/library/hh849808.aspx

      【讨论】:

        【解决方案3】:

        如果你使用 Powershell Test-Connection 命令

        Test-Connection localhost
        

        结果采用如下表格格式:

        如果您想获得丢失的数据包数,您可以执行以下操作。假设您想查看 5 次 ping 中有多少丢包:

           $pingCount = 5
           $x = Test-Connection localhost -count $pingCount
           $lostPackets = $pingCount - $x.count
        

        【讨论】:

        • 这个命令很酷。还能像ping一样上报丢包统计吗?
        • 感谢 Davies 以新的视角回答,至少对我来说是这样。但是@aschipfl 赤手空拳地抓住了它:)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-29
        相关资源
        最近更新 更多