如何为每个ping结果加上时间戳?

102

Ping 默认会返回如下信息:

64 bytes from 203.173.50.132: icmp_seq=0 ttl=244 time=57.746 ms

有没有办法让它添加时间戳?

比如说,

Mon 21 May 2012 15:15:37 EST | 64 bytes from 203.173.50.132: icmp_seq=0 ttl=244 time=57.746 ms

我使用的操作系统是OS X v10.7(Lion),似乎自带一种基于BSD的ping命令。

16个回答

3
您可以在您的~/.bashrc文件中创建一个函数,这样您就可以在控制台上使用ping-t命令:
function ping-t { ping "$1" | while read pong; do echo "$(date): $pong"; done; }

现在你可以在控制台上调用这个函数:
ping-t example.com

2018年3月31日12:58:31 CEST:PING example.com (93.184.216.34),数据大小为56(84)字节。
2018年3月31日12:58:31 CEST:来自93.184.216.34 (93.184.216.34)的64字节:icmp_seq=1 ttl=48 time=208毫秒
2018年3月31日12:58:32 CEST:来自93.184.216.34 (93.184.216.34)的64字节:icmp_seq=2 ttl=48 time=233毫秒


1

您没有指定需要输出的时间戳或间隔,因此我认为它是一个无限循环。根据您的需求进行相应更改即可。

while true
do
   echo -e "`date`|`ping -n -c 1 <IP_TO_PING>|grep 'bytes from'`"
   sleep 2
done

你应该将 grep 部分更改为 egrep '(bytes from|errors)' - rubo77
@rubo77 你可以详细说明为什么要使用'egrep'而不是'grep'吗? - v3nM
使用egrep命令时,只需添加一个正则表达式即可获取错误输出。 - rubo77

1
ping -D -n -O -i1 -W1 8.8.8.8

或者可能。
while true; do \
    ping -n -w1 -W1 -c1 8.8.8.8 \
    | grep -E "rtt|100%" \
    | sed -e "s/^/`date` /g"; \
    sleep 1; \
done

1
我也需要它来监控数据库镜像超时问题的网络问题。我使用以下命令代码:
ping -t Google.com|cmd /q /v /c "(pause&pause)>nul & for /l %a in () do (set /p "data=" && echo(!date! !time! !data!)&ping -n 2 Google.com>nul" >C:\pingtest.txt

您只需要将Google.com修改为您的服务器名称即可。这对我来说非常完美。完成后记得停止此操作。 pingtest.txt文件每秒钟将增加1 KB(左右)。

感谢raymond.cc. https://www.raymond.cc/blog/timestamp-ping-with-hrping/


更新:pingtest.txt 文件每分钟会增加约 4.5 KB。 - DBALUKE HUANG

0

试试这行代码。

while sleep 1;do echo "$(date +%d-%m-%y-%T) $(ping -c 1 whatever.com | gawk 'FNR==2{print "Response from:",$4,$8}')" | tee -a /yourfolder/pingtest.log;done

你需要使用 ctrl-c 来取消它。


使用tee是个好主意,但是-c 1的问题在于会丢失整体统计数据... - minusf

-1

只需使用sed和循环:

ping google.com|while read; do sed -r "s/(.*)/$(date) \1/g"<<<"$REPLY";done

无法工作,因为它只会从命令开始时获取时间戳。 - senden9
更新了我的回答。需要对每行进行sed的重新运行,因此我添加了循环来处理。 - Saboteur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接