1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| #!/bin/bash
#默认第一块网卡为外网卡,检查当前系统是以eth0还是em1作为网卡一,后面会引用网卡名
interface=`ip a|grep -e "eth0" -e "em1"|awk '{print $NF}'|tail -1`
#定义存储结果的函数,以便在任何异常/正常退出前都能保存最新的记录
function tmp_store {
chmod 777 /tmp/receive /tmp/transfer &> /dev/null
#以防以root用户验证脚本时以root创建这两个文件,等nagios以nagios用户调用脚本的时候无法写入新的记录值,导致检测结果不准
cat /proc/net/dev|grep "$interface"|awk '{print $1}'|cut -d ":" -f 2 > /tmp/receive
cat /proc/net/dev|grep "$interface"|awk '{print $9}' > /tmp/transfer
}
#将当时流量统计记录于tmp,然后由nagios调用脚本,定时(5分钟,遇异常隔5分钟再检测)采集新的统计值,
做计算统计出时间段内流量的平均值
RX_bytes_last=`cat /tmp/receive`
TX_bytes_last=`cat /tmp/transfer`
RX_bytes=`cat /proc/net/dev|grep "$interface"|awk '{print $1}'|cut -d ":" -f 2`
TX_bytes=`cat /proc/net/dev|grep "$interface"|awk '{print $9}'`
speed_RX=`echo "scale=0;($RX_bytes - $RX_bytes_last)*8/1024/1024/300"|bc`
#300即5分钟,nagios 每五分钟检测一次流量,统计出来的 单位为Mb
speed_TX=`echo "scale=0;($TX_bytes - $TX_bytes_last)*8/1024/1024/300"|bc`
if [ $speed_RX -gt 5 -a $speed_TX -gt 5 ];then #此处的5,所有对比值,是根据cacti统计出来的基准值
echo "speed_RX=$speed_RX, speed_TX=$speed_TX. both great than normal"
tmp_store;
exit 2
elif [ $speed_RX -gt 5 -o $speed_TX -gt 5 ];then
if [ $speed_RX -gt 5 ];then
echo "receive is $speed_RX Mbps, great than 5Mbps"
tmp_store;
exit 2
else
echo "transfer is $speed_TX Mbps, great than 5Mbps"
tmp_store;
exit 2
fi
else
echo "OK speed_RX=$speed_RX Mbps, speed_TX=$speed_TX Mbps"
tmp_store;
exit 0
fi
|