Context : Our platform's monitoring system is cacti+nagios. Prior to the exception of the traffic alarm settings, cacti up to is there is a plug-in can time alarm, but can not use our own SMS interface (Nagios with the purchase of SMS interface), so want to write a script with Nagios to achieve basic traffic anomaly alarm.
script Idea :/proc/net/dev take out the total number of kilobytes currently flowing through the network card (receive and send), read the two values again after the detection interval,
Subtract is both the increment in the interval, and then calculates the average flow within the interval, comparing it to the baseline traffic, triggering the Nagios alarm event
Limitations : We only detect the external network card traffic, and the default EM1 network card for the external network card (according to the actual situation of your own adjustment)
#!/bin/bash #默认第一块网卡为外网卡, check whether the current system is eth0 or EM1 as a NIC, followed by a reference Card name interface= ' ip a|grep -e "eth0" -e "em1" |awk ' {print $NF} ' |tail -1 ' #定义存储结果的函数 to keep up-to-date records before any abnormal/normal exit function tmp_store { chmod 777 /tmp/receive /tmp/transfer &> / dev/null #以防以root用户验证脚本时以root创建这两个文件, When Nagios does not write new record values when the user invokes the script in Nagios, the result is not 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, then called by Nagios Script, timed (5 minutes, Abnormal interval of 5 minutes before detection) to collect new statistical values, to calculate the average amount of traffic in the time periodValue 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 detection of traffic every five minutes, the statistics of the unit is 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, all contrast values, are based on the cacti statistics of the benchmark values 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
Nagios traffic monitoring and alerting for shell scripts