原 在Windows和Linux下,为ping命令结果增加时间信息(持续ping写入日志)
Tags: 原创LinuxWindowsping写入日志持续ping时间
Windows系统
Windows系统可以使用PowerShell来执行Ping指令,并用Foreach语句来为每一行输出添加时间信息。例如,如果要Ping百度的网址,并在每行前加上当前日期和时间,可以输入以下命令:
1 2 3 4 5 | powershell ping -t www.baidu.com |Foreach { "{0} - {1}" -f (Get-Date),$_} -- 记录到文件 ping -t www.baidu.com |Foreach { "{0} - {1}" -f (Get-Date),$_} > d:\ping_result.log |
缺点:没有最后的统计信息了,需要加上-n参数且不能提前结束才可以。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | C:\Users\xmm>powershell Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows PS C:\Users\xmm> ping -t www.baidu.com |Foreach { "{0} - {1}" -f (Get-Date),$_} 2023/12/16 11:25:04 - 2023/12/16 11:25:04 - Pinging www.a.shifen.com [183.2.172.185] with 32 bytes of data: 2023/12/16 11:25:04 - Reply from 183.2.172.185: bytes=32 time=37ms TTL=51 2023/12/16 11:25:05 - Reply from 183.2.172.185: bytes=32 time=41ms TTL=51 2023/12/16 11:25:06 - Reply from 183.2.172.185: bytes=32 time=38ms TTL=51 2023/12/16 11:25:07 - Reply from 183.2.172.185: bytes=32 time=39ms TTL=51 PS C:\Users\xmm> PS C:\Users\xmm> ping -t www.baidu.com -n 6 |Foreach { "{0} - {1}" -f (Get-Date),$_} 2023/12/16 11:36:42 - 2023/12/16 11:36:42 - Pinging www.a.shifen.com [183.2.172.42] with 32 bytes of data: 2023/12/16 11:36:42 - Reply from 183.2.172.42: bytes=32 time=34ms TTL=51 2023/12/16 11:36:43 - Reply from 183.2.172.42: bytes=32 time=35ms TTL=51 2023/12/16 11:36:44 - Reply from 183.2.172.42: bytes=32 time=35ms TTL=51 2023/12/16 11:36:45 - Reply from 183.2.172.42: bytes=32 time=35ms TTL=51 2023/12/16 11:36:46 - Reply from 183.2.172.42: bytes=32 time=34ms TTL=51 2023/12/16 11:36:47 - Reply from 183.2.172.42: bytes=32 time=34ms TTL=51 2023/12/16 11:36:47 - 2023/12/16 11:36:47 - Ping statistics for 183.2.172.42: 2023/12/16 11:36:47 - Packets: Sent = 6, Received = 6, Lost = 0 (0% loss), 2023/12/16 11:36:47 - Approximate round trip times in milli-seconds: 2023/12/16 11:36:47 - Minimum = 34ms, Maximum = 35ms, Average = 34ms PS C:\Users\xmm> |
Linux系统
Linux系统:可以使用awk或sed等工具来为Ping指令的输出添加时间信息。例如,如果要Ping百度的网址,并在每行前加上当前日期和时间,可以输入以下命令:
1 2 3 4 5 6 7 8 9 10 | ping www.baidu.com | awk '{ print strftime("%Y-%m-%d %H:%M:%S",systime())"\t"$0 }' -- 或者 ping www.baidu.com -c 5 | sed "s/^/$(date) /" ping www.example.com | while read pong; do echo "$(date): $pong"; done ping www.example.com | while read pong; do echo "$(date +"%Y-%m-%d %H:%M:%S.%3N"): $pong"; done ping www.example.com | while read pong; do echo "$(date +"%Y-%m-%d %H:%M:%S.%3N"): $pong"; done > /tmp/aa.log |