Skip to content

Instantly share code, notes, and snippets.

@yurenchen000
Created April 10, 2020 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurenchen000/efac1abc5a255d29c8cd40f19e82c408 to your computer and use it in GitHub Desktop.
Save yurenchen000/efac1abc5a255d29c8cd40f19e82c408 to your computer and use it in GitHub Desktop.
linux ping cmd with timestamp

https://askubuntu.com/a/400273/413480

1. time from ping -D

Another possibility to use the ping -D option which gets you the timestamp as Unix time.

tilo@t-ubuntu:~$ ping google.com -D
PING google.com (173.194.33.73) 56(84) bytes of data.
[1388886989.442413] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=1 ttl=57 time=11.1 ms
[1388886990.443845] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=2 ttl=57 time=11.0 ms
[1388886991.445200] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=3 ttl=57 time=10.8 ms
[1388886992.446617] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=4 ttl=57 time=10.9 ms
^C
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 10.860/11.005/11.139/0.123 ms
tilo@t-ubuntu:~$ 

here is a awk cmd to parse timestamp to date format:

$ ping -D 10.1.1.1 | awk '{ if(gsub(/\[|\]/, "", $1)) $1=strftime("[%F %T]", $1); print}'
PING 10.1.1.1 (10.1.1.1) 56(84) bytes of data.
[2020-04-10 19:25:08] 64 bytes from 10.1.1.1: icmp_seq=1 ttl=63 time=14.1 ms
[2020-04-10 19:25:09] 64 bytes from 10.1.1.1: icmp_seq=2 ttl=63 time=12.9 ms
[2020-04-10 19:25:10] 64 bytes from 10.1.1.1: icmp_seq=3 ttl=63 time=12.0 ms
^C

PS: awk may full-buffered with pipe, a fflush() after print will fix:

ping.ts(){
    if [ -t 1 ]; then
        ping -D "$@" | awk '{ if(gsub(/\[|\]/, "", $1)) $1=strftime("[\033[34m%F %T\033[0m]", $1); print; fflush()}'
    else
        ping -D "$@" | awk '{ if(gsub(/\[|\]/, "", $1)) $1=strftime("[%F %T]", $1); print; fflush()}'
    fi  
}

ping.ts 10.1.1.1

2. time from date

Here a version of "Achu" command with slightly different format:

ping www.google.com -i 10 -c 3000 | while read pong; do echo "$(date +%Y-%m-%d_%H%M%S): $pong"; done >PingTest_2014-01-04.log

That gets you:

2014-01-04_175748: 64 bytes from sea09s16-in-f19.1e100.net (173.194.33.115): icmp_req=13 ttl=57 time=10.5 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment