fjptec-xm 发表于 2018-8-25 08:03:35

nagios 流量监控和报警的shell脚本

#!/bin/bash  
#by ljk
  
   #默认第一块网卡为外网卡,检查当前系统是以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"|sed 's/^ *//g'|awk -F'[ :]+' '{print $2}' > /tmp/receive
  
       cat /proc/net/dev|grep "$interface"|sed 's/^ *//g'|awk -F'[ :]+' '{print $10}' > /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"|sed 's/^ *//g'|awk -F'[ :]+' '{print $2}'`
  
   TX_bytes=`cat /proc/net/dev|grep "$interface"|sed 's/^ *//g'|awk -F'[ :]+' '{print $10}'`
  

  
   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,是我们的基准值,各位自行调整
  
      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


页: [1]
查看完整版本: nagios 流量监控和报警的shell脚本