Shell长ping脚本监控网络状态

linux环境使用ping命令+时间戳记录到文件里面

生产环境中, 网络是否稳定(网络时延)是一个很重要的指标. 为了方便检查网络时延的大小, 我们可以通过ping命令实现长时间的网络监控。


一、ping命令的使用

1、 常用参数

-i: 每次执行ping操作的间隔时间, 默认是1s;

-c: 执行ping操作的次数, 默认是一直执行, 除非被中断;

-s:指定执行ping操作时发送的包的大小, 默认是56B, 添加报文头之后, 最终发送的是64B.


2、 使用示例

# 在终端 ping 某个地址, 执行10次
# ping 112.80.248.75 -c 10 | awk '{ print $0"\t" strftime("%H:%M:%S",systime()) } '

image.png

#后台运行记录到文件里面,但终端不能断开的,语句如下:
nohup ping 112.80.248.75 -c 10 | awk '{ print $0"\t" strftime("%H:%M:%S",systime()) } '>ping1.log &


2.1、日期时间在后面:

# ping 112.80.248.75 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime()); fflush()}' >> long_ping.txt

PING 112.80.248.75 (112.80.248.75) 56(84) bytes of data.       2020-04-03 16:59:44
64 bytes from 112.80.248.75: icmp_seq=1 ttl=55 time=3.66 ms     2020-04-03 16:59:44
64 bytes from 112.80.248.75: icmp_seq=2 ttl=55 time=4.90 ms     2020-04-03 16:59:45
64 bytes from 112.80.248.75: icmp_seq=3 ttl=55 time=4.02 ms     2020-04-03 16:59:46


2.2、日期时间在前面:

# ping 112.80.248.75 | awk '{ print strftime("%Y.%m.%d %H:%M:%S",systime())"\t" $0; fflush() }' >> long_ping.txt

2020.04.03 17:00:36     PING 112.80.248.75 (112.80.248.75) 56(84) bytes of data.
2020.04.03 17:00:36     64 bytes from 112.80.248.75: icmp_seq=1 ttl=55 time=3.22 ms
2020.04.03 17:00:37     64 bytes from 112.80.248.75: icmp_seq=2 ttl=55 time=3.72 ms
2020.04.03 17:00:38     64 bytes from 112.80.248.75: icmp_seq=3 ttl=55 time=4.91 ms
2020.04.03 17:00:39     64 bytes from 112.80.248.75: icmp_seq=4 ttl=55 time=3.95 ms

注意:使用fflush(),不然文件不会有信息,因为awk也是有缓存的。

下面未加fflush(),执行命令生成文件会等一会才会有信息打印到文件里

ping 112.80.248.75 | awk '{ print strftime("%Y.%m.%d %H:%M:%S",systime())"\t" $0 }'>> long_ping.txt &


二、通过脚本记录时间戳

为了方便后期查看, 也防止退出终端时命令被中断, 我们可以通过后台运行命令(脚本)的方式进行操作.

脚本内容如下:

# vi long_ping.sh 
#!/bin/bash
ping 112.80.248.75 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime()); fflush()}' >> long_ping.txt

注意: 只有当脚本运行结束(或被kill掉), awk命令 才会将结果输出到文件中.

为防止脚本被中断, 可以通过 nohup 令脚本在后台执行:

nohup sh long_ping.sh &

要结束后台进程, 可通过下述方式查找并kill:

# ps -ef |grep long
root 17341 17236  0 16:46 pts/3 00:00:00 sh long_ping.sh
root 17351 17236  0 16:47 pts/3 00:00:00 grep --color=auto long


猜你喜欢

转载自blog.51cto.com/meiling/2484753