Cómo ordenar la hora y la fecha de visualización de "Ping"


39

Cuando hago ping tengo esta pantalla:

> ping -i 4 www.google.fr 
64 bytes from wi-in-f94.1e100.net (173.194.67.94): icmp_seq=503 ttl=46 time=45.5 ms
.......
.......
64 bytes from wi-in-f94.1e100.net (173.194.67.94): icmp_seq=508 ttl=46 time=44.9 ms
64 bytes from wi-in-f94.1e100.net (173.194.67.94): icmp_seq=509 ttl=46 time=45.1 ms

Me gustaría tener el tiempo del ping antes.

Algo como:

> (right functions) + ping -i 7 www.google.fr 
mardi 15 mai 2012, 10:29:06 (UTC+0200) - 64 bytes from wi-in-f94.1e100.net (173.194.67.94): icmp_seq=503 ttl=46 time=45.5 ms
.......
.......
mardi 15 mai 2012, 10:29:13 (UTC+0200) - 64 bytes from wi-in-f94.1e100.net (173.194.67.94): icmp_seq=508 ttl=46 time=44.9 ms
mardi 15 mai 2012, 10:29:20 (UTC+0200) - 64 bytes from wi-in-f94.1e100.net (173.194.67.94): icmp_seq=509 ttl=46 time=45.1 ms

¿Cómo haría esto en una línea de comando (si es posible)?


Respuestas:


77

Utilizar:

ping www.google.fr | while read pong; do echo "$(date): $pong"; done

Obtendrás el resultado así:

ingrese la descripción de la imagen aquí


1
Wow muy agradable. Y útil para aprender cosas de shell. ¡Gracias!
Olivier Pons

Tiempo de actividad en segundosping 192.168.70.1 | while read pong; do echo "$(awk '{print $1}' /proc/uptime): $pong"; done
dps

16

Otra posibilidad de utilizar la ping -Dopción que le proporciona la marca de tiempo como hora Unix.

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:~$ 

Aquí una versión del comando "Achu" con un formato ligeramente diferente:

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

Eso te atrapa:

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

6

Hay una utilidad llamada ts, que lee stdin, agrega marcas de tiempo y lo escribe en stdout:

me@my-laptop:~$ ping localhost | ts
Nov 08 09:15:41 PING localhost (127.0.0.1) 56(84) bytes of data.
Nov 08 09:15:41 64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.060 ms
Nov 08 09:15:42 64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.098 ms
Nov 08 09:15:43 64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.082 ms
Nov 08 09:15:44 64 bytes from localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.091 ms

Se puede instalar en Ubuntu con .sudo apt install moreutils


1
+1 Como nota al margen: ts no está instalado en Ubuntu (al menos 16.04) de forma predeterminada, por lo que debe instalarlo comoapt install moreutils
dmikam

3

También puede usar gawk(o awk, si sus /etc/alternatives/awkpuntos a /usr/bin/gawk):

ping -c 4 www.google.fr | gawk '{print strftime("%c: ") $0}'

Esto es similar al enfoque en la respuesta de Achu , pero pingla salida de la canalización se dirige a gawkun bucle de shell que llama date. Al igual que con ese enfoque, funciona sin él -c, pero si no pasa para hacer que el ping se detenga después de n pings, y detiene el ciclo con + , no imprimirá las estadísticas habituales.-c nCtrlCping

ek@Io:~$ ping -c 4 www.google.fr | gawk '{print strftime("%c: ") $0}'
Tue 03 Jan 2017 10:09:51 AM EST: PING www.google.fr (216.58.193.99) 56(84) bytes of data.
Tue 03 Jan 2017 10:09:51 AM EST: 64 bytes from sea15s08-in-f3.1e100.net (216.58.193.99): icmp_seq=1 ttl=51 time=327 ms
Tue 03 Jan 2017 10:09:52 AM EST: 64 bytes from sea15s08-in-f3.1e100.net (216.58.193.99): icmp_seq=2 ttl=51 time=302 ms
Tue 03 Jan 2017 10:09:53 AM EST: 64 bytes from sea15s08-in-f3.1e100.net (216.58.193.99): icmp_seq=3 ttl=51 time=282 ms
Tue 03 Jan 2017 10:09:54 AM EST: 64 bytes from sea15s08-in-f3.1e100.net (216.58.193.99): icmp_seq=4 ttl=51 time=349 ms
Tue 03 Jan 2017 10:09:54 AM EST:
Tue 03 Jan 2017 10:09:54 AM EST: --- www.google.fr ping statistics ---
Tue 03 Jan 2017 10:09:54 AM EST: 4 packets transmitted, 4 received, 0% packet loss, time 3003ms
Tue 03 Jan 2017 10:09:54 AM EST: rtt min/avg/max/mdev = 282.035/315.227/349.166/25.398 ms
ek@Io:~$ ping www.google.fr | gawk '{print strftime("%c: ") $0}'
Tue 03 Jan 2017 10:10:35 AM EST: PING www.google.fr (216.58.193.99) 56(84) bytes of data.
Tue 03 Jan 2017 10:10:35 AM EST: 64 bytes from sea15s08-in-f99.1e100.net (216.58.193.99): icmp_seq=1 ttl=51 time=305 ms
Tue 03 Jan 2017 10:10:35 AM EST: 64 bytes from sea15s08-in-f99.1e100.net (216.58.193.99): icmp_seq=2 ttl=51 time=365 ms
Tue 03 Jan 2017 10:10:36 AM EST: 64 bytes from sea15s08-in-f99.1e100.net (216.58.193.99): icmp_seq=3 ttl=51 time=390 ms
Tue 03 Jan 2017 10:10:38 AM EST: 64 bytes from sea15s08-in-f99.1e100.net (216.58.193.99): icmp_seq=4 ttl=51 time=824 ms
Tue 03 Jan 2017 10:10:38 AM EST: 64 bytes from sea15s08-in-f99.1e100.net (216.58.193.99): icmp_seq=5 ttl=51 time=287 ms
^C

Esto sucede ya sea que pingla salida se canalice a gawkun whilebucle de shell . La razón es que el comando en el lado derecho de la tubería, en lugar de ping, recibe SIGINT cuando se presiona Ctrl+ C, y pingno sabe imprimir las estadísticas antes de terminar.

Si ha corrido pingsin -cen el lado izquierdo de una tubería (como se muestra arriba) y desea terminarlo de tal manera que todavía imprima las estadísticas, entonces en lugar de presionar Ctrl+ Cen el terminal donde está corriendo, puede ejecutar desde otro terminal, reemplazando con el ID de proceso del comando. Si solo está ejecutando una instancia de, entonces simplemente podría usar .kill -INT PIDPIDpingpingkillall -INT ping

Alternativamente, puede reemplazar el pingcomando en el lado izquierdo de la tubería con un comando que ejecuta un shell, informa el ID del proceso de ese shell y luego reemplaza ese shell con el pingcomando (haciendo que tenga el mismo PID):

sh -c 'echo $$; exec ping www.google.fr' | gawk '{print strftime("%c: ") $0}'

Luego, la primera línea de salida mostrará el ID del proceso del pingcomando (que generalmente será diferente cada vez). Se vería así, pero con una fecha y hora diferentes y probablemente una ID de proceso diferente:

Tue 20 Mar 2018 12:11:13 PM EDT: 7557

Luego, desde otro terminal, puede ejecutar kill -INT 7557, reemplazando 7557con el ID de proceso real que vio, para finalizar el pingcomando de tal manera que haga que imprima estadísticas.

(Si aprovecha las funciones de control de trabajo de su shell , también puede lograr esto dentro de la misma terminal. Pero si desea copiar texto desde su terminal sin tener que quitar ninguna parte extrañosa donde ejecutó comandos en esa terminal, entonces debe terminar pingdesde un terminal separado).

Otras lecturas:


¿hay alguna manera de enviar ctrl + c a ping primero?
atti

1
@atti Sí, puede enviar SIGINT(que es lo que hace presionar Ctrl + C) al pingproceso específicamente, usando killo killall. He ampliado esta respuesta con detalles.
Eliah Kagan

Buen uso de awk. +1
enviado el

0
ping google.in | xargs -n1 -i bash -c 'echo `date +"%Y-%m-%d %H:%M:%S"`" {}"'

Si está interesado en guardarlo en un archivo, escriba el siguiente comando en el terminal

ping google.in | xargs -n1 -i bash -c 'echo `date +"%Y-%m-%d %H:%M:%S"`" {}"' >> "/home/name_of_your_computer/Desktop/Ping_Test.txt"

No necesita crear ningún archivo de texto, lo hará automáticamente

Ping_Test.txt

2018-04-19 15:35:53 PING google.in (216.58.203.164) 56(84) bytes of data.
2018-04-19 15:35:53 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=1 ttl=57 time=23.0 ms
2018-04-19 15:35:53 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=2 ttl=57 time=38.8 ms
2018-04-19 15:35:54 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=3 ttl=57 time=32.6 ms
2018-04-19 15:35:55 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=4 ttl=57 time=22.2 ms
2018-04-19 15:35:56 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=5 ttl=57 time=22.1 ms
2018-04-19 15:35:59 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=7 ttl=57 time=23.6 ms
2018-04-19 15:36:00 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=8 ttl=57 time=22.6 ms
2018-04-19 15:36:01 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=9 ttl=57 time=22.3 ms
2018-04-19 15:36:02 64 bytes from bom07s11-in-f4.1e100.net (216.58.203.164): icmp_seq=10 ttl=57 time=26.3 ms

-1

(gracias a Achu y Eliah Kagan por las ideas) hay una manera de

  • agregar tiempo a la pingsalida
  • mantener notas al pie de ping
  • y terminar toda esta construcción con ctrl+c

para hacer esto, se debe indicar a la parte derecha del comando (después de la tubería) que ignore el SIGINTuso de trap "" INT:

$ ping www.google.fr | bash -c 'trap "" INT; awk "{print strftime(\"%c - \") \$0}"'  
lun 26 Mar 2018 22:05:08 +0300 - PING www.google.fr (173.194.73.94) 56(84) bytes of data.
lun 26 Mar 2018 22:05:08 +0300 - 64 bytes from lq-in-f94.1e100.net (173.194.73.94): icmp_seq=1 ttl=47 time=19.6 ms
lun 26 Mar 2018 22:05:09 +0300 - 64 bytes from lq-in-f94.1e100.net (173.194.73.94): icmp_seq=2 ttl=47 time=20.1 ms
^Clun 26 Mar 2018 22:05:09 +0300 - 
lun 26 Mar 2018 22:05:09 +0300 - --- www.google.fr ping statistics ---
lun 26 Mar 2018 22:05:09 +0300 - 2 packets transmitted, 2 received, 0% packet loss, time 1000ms
lun 26 Mar 2018 22:05:09 +0300 - rtt min/avg/max/mdev = 19.619/19.866/20.114/0.284 ms
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.