Acfe 发表于 2019-1-25 09:44:33

自定义zabbix监控脚本

  1.在客户端修改配置文件/etc/zabbix/zabbix_agentd.conf    #为了方便这里是用yum安装的zabbix
  
需要改动两个地方:

[*]  (1)UnsafeUserParameters=1

[*]  (2) UserParameter=my.net.if
[*],/usr/local/sbin/zabbix/net.sh $1 $2   #其中UserParameter用来自定义键值,名称可以自定义,如果自己写的脚本带有参数,那么就需要加
[*],这是固定写法;如果脚本压根就没有什么参数,那么就直接UserParameter=my.net.if=my.net.if就可以了。逗号后面就是我们写的脚本的路径了,再后面就是脚本要用到的参数,没有参数就不用写。
  

  2. 编写脚本
vim/usr/local/sbin/zabbix/net.sh   #我随便写的一个简单的监控网卡流量的脚本

  #!/bin/bash
  eth=$1
  io=$2
  net_file="/proc/net/dev"
  if [ $io == "in" ]
  then
      n_new=`grep "$eth" $net_file|awk '{print $2}'`
      d_new=`date +%s`
      if [ -z $n_new ]
      then
         echo "not found $eth"
         exit
      fi
  

      if [ -f /tmp/$eth\_neti.log ]            ##neti表示输入流量,neto表示输出流量
      then
         n_old=`tail -1 /tmp/$eth\_neti.log`
         n=$[$n_new-$n_old]
         d_old=`tail -2 /tmp/$eth\_neti.log|head -1`
         d=$[$d_new-$d_old]
         if_net=`echo "$n/$d"|bc`            ##求d_old到d_new时间段内每秒平均流量单位byte
         echo $if_net
         echo $d_new >> /tmp/$eth\_neti.log
         echo $n_new >> /tmp/$eth\_neti.log
      else
         touch /tmp/$eth\_neti.log
         chown zabbix /tmp/$eth\_neti.log
         echo $d_new >> /tmp/$eth\_neti.log
         echo $n_new >> /tmp/$eth\_neti.log
         echo "please again try script"
         exit
      fi
  

  elif [ $io == "out" ]
  then
      n_new=`grep "$eth" $net_file|awk '{print $10}'`
      d_new=`date +%s`
      if [ -z $n_new ]
      then
         echo "not found $eth"
         exit
      fi
  

      if [ -f /tmp/$eth\_neto.log ]
      then
         n_old=`tail -1 /tmp/$eth\_neto.log`
         n=$[$n_new-$n_old]
         d_old=`tail -2 /tmp/$eth\_neto.log|head -1`
         d=$[$d_new-$d_old]
         if_net=`echo "$n/$d"|bc`
         echo $if_net
         echo $d_new >> /tmp/$eth\_neto.log
         echo $n_new >> /tmp/$eth\_neto.log
      else
         touch /tmp/$eth\_neto.log
         chown zabbix /tmp/$eth\_neto.log
         echo $d_new >> /tmp/$eth\_neto.log
         echo $n_new >> /tmp/$eth\_neto.log
         echo "please again try script"
         exit
      fi
  

  else
      if grep -q "$eth" $net_file
      then
         echo 0
      else
         echo "not found $eth"
      fi
  fi
  

  这个脚本的思路,就是通过查看文件 /proc/net/dev里面的数值,来计算实时网卡流量,其实我算的是一个平均值,分为进和出。如果这个脚本每隔1分钟执行一次,那么算出来的流量值就是1分钟的平值。该脚本有两个参数第一个是网卡名字如:eth0,第二个是in或者out也就是进或者出流量,该脚本可以计算机器上所有网卡的进出流量只要更改第一个参数eth0,eth1,lo等就可以了。但是有点遗憾,第一次运行时会自动创建*net.log的临时文件,第二次运行脚本才能得到数值,当然你也可以手动创建文件并写入时间戳但是我觉得没必要。
  

  3. 检查脚本是否可用
在服务端执行
zabbix_get -s IP -p10050 -k "my.net.if"   ##这个IP是客户端的ip
  如果可以返回数值说明没问题了。
  
4. 接着在浏览器上zabbix里面配置
组态 --> 主机 --> 项目--> 创建监控项
名称 “eth0_net_out”   ##名字可以随意也可以写中文
类型默认“zabbix代理”
键值"my.net.if"
存档 ok

  当然你也可以把,等等都加入监控项。
  




ha00012 发表于 2019-2-14 09:53:58

好帖子
页: [1]
查看完整版本: 自定义zabbix监控脚本