2016年2月4日木曜日

Pingコマンドの結果にタイムスタンプをつける Linux編

Linuxでpingコマンドを実行する際に、時刻情報を付与することで証跡として使用したい場合などのメモ。


①dateコマンドとWhile文の組み合わせた方法

ping 8.8.8.8 | while read pi; do echo "$(date '+[%m/%d %H:%M:%S]') $pi"; done

[root@localhost ~]# ping 8.8.8.8 | while read pi; do echo "$(date '+[%m/%d %H:%M:%S]') $pi"; done
[02/04 00:04:58] PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
[02/04 00:04:58] 64 bytes from 8.8.8.8: icmp_seq=1 ttl=55 time=1.32 ms
[02/04 00:04:59] 64 bytes from 8.8.8.8: icmp_seq=2 ttl=55 time=1.16 ms
[02/04 00:05:00] 64 bytes from 8.8.8.8: icmp_seq=3 ttl=55 time=1.04 ms
[02/04 00:05:01] 64 bytes from 8.8.8.8: icmp_seq=4 ttl=55 time=1.14 ms
[02/04 00:05:02] 64 bytes from 8.8.8.8: icmp_seq=5 ttl=55 time=1.06 ms
[02/04 00:05:03] 64 bytes from 8.8.8.8: icmp_seq=6 ttl=55 time=1.18 ms


xargsコマンドを使用した方法

ping 8.8.8.8 | xargs -L 1 -I '{}' date '+[%m/%d %H:%M:%S] {}'

[root@localhost  ~]# ping 8.8.8.8 | xargs -L 1 -I '{}' date '+[%m/%d %H:%M:%S] {}'
[02/04 00:06:44] PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
[02/04 00:06:44] 64 bytes from 8.8.8.8: icmp_seq=1 ttl=55 time=1.41 ms
[02/04 00:06:45] 64 bytes from 8.8.8.8: icmp_seq=2 ttl=55 time=1.05 ms
[02/04 00:06:46] 64 bytes from 8.8.8.8: icmp_seq=3 ttl=55 time=1.17 ms
[02/04 00:06:47] 64 bytes from 8.8.8.8: icmp_seq=4 ttl=55 time=1.07 ms
[02/04 00:06:48] 64 bytes from 8.8.8.8: icmp_seq=5 ttl=55 time=1.39 ms
[02/04 00:06:49] 64 bytes from 8.8.8.8: icmp_seq=6 ttl=55 time=1.08 ms


perlを用いた方法(要Perl環境)

ping 8.8.8.8 | perl -MPOSIX -pe 'print strftime("\[%m/%d %H:%M:%S\] ", localtime)'


[root@localhost ~]# ping 8.8.8.8 | perl -MPOSIX -pe 'print strftime("\[%m/%d %H:%M:%S\] ", localtime)'
[02/04 00:08:57] PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
[02/04 00:08:57] 64 bytes from 8.8.8.8: icmp_seq=1 ttl=55 time=1.32 ms
[02/04 00:08:58] 64 bytes from 8.8.8.8: icmp_seq=2 ttl=55 time=1.16 ms
[02/04 00:08:59] 64 bytes from 8.8.8.8: icmp_seq=3 ttl=55 time=1.08 ms
[02/04 00:09:00] 64 bytes from 8.8.8.8: icmp_seq=4 ttl=55 time=1.07 ms
[02/04 00:09:01] 64 bytes from 8.8.8.8: icmp_seq=5 ttl=55 time=1.07 ms


日付の書式文字列は必要に応じて変更すること
あと、あまり8.8.8.8に迷惑をかけないこと

0 件のコメント:

コメントを投稿