network_monitor - YUHAO-ZX/StudyCollection GitHub Wiki
###说明:通过linux的cron定时任务来调度shell程序
1.定时任务:crontab -e
2.定义:*/10 * * * * bash /home/yuey/network_monitor.sh 表示每10分钟执行一次network_monitor.sh脚本
3.(debian)如果没有生效就重启:/etc/init.d/cron restart
###代码:
#!/bin/bash
ping=/bin/ping
ave_limit=1
max_limit=1
loss_limit=1
sh_dir=/home/yuey/
user=`id -u`
hosts=( "10.0.18.64" "10.0.18.65" "10.16.18.10" "10.17.46.40" "10.17.46.41" "10.17.46.38" "10.16.36.22" "10.1.23.5" "10.0.131.1" "10.0.131.2" "10.0.131.3" "10.0.131.4" "10.0.131.5" "10.0.131.6" "10.0.131.7" "10.0.131.8" "10.0.131.9" "10.0.131.10" "10.0.131.11" "10.0.131.12" "10.0.131.13" "10.0.131.14" "10.0.131.15" "10.0.131.16" "10.0.131.17" "10.0.131.18" "10.0.131.19" "10.0.131.20" "10.16.18.9" "10.17.46.39" "10.16.36.22:9000:1")
#main
#root权限
if [ "$user" -ne 0 ];then
echo "must root !!"
exit 1
fi
result=""
#主循环遍历机器 遍历的使用方法
for HOST in ${hosts[@]};do
#true
echo $HOST
#-c 10 表示ping10次结束
$ping -W 2 -f -c 10 $HOST > /home/yuey/monitor/$HOST.log
#分析日志,int($2) 做数据转换 ``用于shell中执行命令并返回结果
ave=`grep 'min/avg/max/mdev' /home/yuey/monitor/$HOST.log | awk '{print $4}' | awk -F '/' '{print int($2)}'`
max=`grep 'min/avg/max/mdev' /home/yuey/monitor/$HOST.log | awk '{print $4}' | awk -F '/' '{print int($3)}'`
loss=`grep 'packets transmitted' /home/yuey/monitor/$HOST.log | awk '{print $6}' | awk -F '%' '{print int($1)}'`
echo $ave $max $loss
if [ $ave -ge $ave_limit ] || [ $max -ge $max_limit ] || [ $loss -ge $loss_limit ];then
#字符串拼接的方式
result="$result""ip:[$HOST]\tping10次,平均耗时:[$ave ms]\t最大耗时:[$max ms]\t丢包率:[$loss %]\r\n"
fi
done
#echo格式化输出
echo -e $result
if [ "$result" != "" ];then
result="promotion网络监控\r\n""$result"
#发送邮件 的方式
echo -e $result | mail -s "promotion线上机器网络延时监控告警" [email protected],[email protected]
fi