zabbix自动化

基于zabbix2.0.2版本


一、定期报表功能

根据screen名称将screen所展示的内容发给指定用户的邮件。

1.1配置文件:config.ini

将screen的名称以逗号分隔,之后以---与report收件地址分隔。多个地址可以分号分隔

WEB_outlets.idc3(CPU),WEB_outlets.idc3(TCP)[email protected]
WEB_music.idc3(MEM)[email protected];[email protected]

1.2主程序:create_script.sh

默认查看近期一周的数据。

脚本会以(为分隔符,拿到同一类screen的名称,里面可以包含cpu、mem等子分类。

#!/bin/bash
#create report script.
config='config.ini'
dbuser='shanks'
dbpass='shanks123'
dbhost='localhost'
dbport=3306
dbname='zabbix'
for zone in `awk -F\('{print $1}' ${config}`
do
  mail_user=`grep -w "${zone}"${config}|awk -F--- '{print $2}'`
cat << hello-DD >${zone}
#!/bin/bash
now=\`date+"%Y%m%d%H%M%S"\`
now_s=\`date+"%s"\`
day_now=\`date+"%d"\`
week=604800
day=\${week}
width=500
url='http://zabbix.shanks.com/chart2.php?'
/usr/sbin/sendmail [email protected] -t << EOF
To:${mail_user}
Subject:ZABBIX-REPORT-${zone}
Content-type:text/html;charset=UTF-8
hello-DD
  for screen in `grep -w "${zone}"${config} |awk -F--- '{print $1}'|sed 's/,/ /g'`
  do
    echo"

${screen}

">> ${zone} echo "" >> ${zone} #global set is over,now set the graph. #get all of this screen's graphid. graphids=`mysql -u${dbuser} -p${dbpass}-h${dbhost} -P${dbport} ${dbname} -e "select resourceid from screens_itemswhere screenid=(select screenid from screens wherename=\"${screen}\")"` jishu=1 num_graphids=`echo${graphids##*resourceid}|awk '{print NR}'` echo ${num_graphids} for graphid in `echo${graphids##*resourceid}` do module=$((${jishu}%2)) if [ ${module} == 1 ] then if [ ${jishu} ==${num_graphids} ] then echo"">> ${zone} else echo"">> ${zone} fi elif [ ${module} == 0 ] then echo "">> ${zone} fi jishu=$((jishu+1)) done echo "">> ${zone} done echo "EOF" >> ${zone} done

1.3生成文件:WEB_music.idc3 WEB_outlets.idc3

之后将WEB_music.idc3 WEB_outlets.idc3赋予可执行权限,并用cron执行即可。

二、批量添加screen

2.1主配置文件:screen.ini

[zabbix]
host=192.168.122.100
db=zabbix
dbuser=shanks
dbpasswd=shanks123
api=http://192.168.122.101/api_jsonrpc.php
zbuser=admin
zbpasswd=shanks

2.2 监控项对应关系:item.ini

显示名:graph名称

{
"CPU":"CPU",
"MEM":"mem_free",
"DISK":"DISK",
"TRAFFIC":"traffic",
"TCP":"fluxconns",
"SWAP":"swap_free"
}

2.3 主机、screen对应关系文件:host.ini

Screen的名称以【】括起,其对应的主机以host=定义,多台以逗号分隔。

[WEB_shanks.com]
host=web-192.168.122.99-IDC2,web-192.168.122.100-IDC2
[WEB_pp711.com]
host=web-192.168.122.101-IDC2,web-192.168.122.102-IDC2

2.4主程序:screen.py

#!/usr/bin/python
#encoding:gb2312
import MySQLdb
import ConfigParser
import commands,json,sys,os
#def GetAuthStr():
  authstr={}
  cmd='''curl -i -s -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","method":"user.login","params":{"user":"'''+zbuser+'''","password":"'''+zbpasswd+'''"},"auth":null,"id":0}' '''+api+'|tail -1'
  #print cmd
  out=commands.getoutput(cmd)
  #json
       authstr=json.loads(out)
  return authstr["result"]
def GetScreenId():
  conn=MySQLdb.connect(host=host,user=dbuser,passwd=dbpasswd,port=3306,db=db)
  sql='select max(screenid)+1 from screens'
  cursor=conn.cursor()
  cursor.execute(sql)
  result=cursor.fetchall()
  for record in result:
    return record[0]
  cursor.close()
  conn.close()
#graphid
def GetResourceId(item,ip):
  conn=MySQLdb.connect(host=host,user=dbuser,passwd=dbpasswd,port=3306,db=db)
  sql="select DISTINCT a.graphid,a.name,d.host from graphs a,graphs_items b,items c,hosts d\
     where a.graphid=b.graphid andb.itemid=c.itemid and c.hostid=d.hostid\
     and d.host='"+ip+"' anda.name='"+item+"'"
  #print sql
  cursor=conn.cursor()
  cursor.execute(sql)
  result=cursor.fetchall()
  for record in result:
    return record[0]
  cursor.close()
  conn.close()
#screeitems
def GetScreeItems(screenid,resourceid,x,y):
  screenitem='{"screenid":"'+str(screenid)+'","resourcetype":0,"resourceid": "'+str(resourceid)+'","rowspan":0,"colspan": 0,"width":500,"height":100,"x":'+str(x)+',"y": '+str(y)+'}'
  return screenitem
if __name__=='__main__':
  if(len(sys.argv)<1):
    print"usage:"+sys.argv[0]+"domain itemidc\nex:"+sys.argv[0]+" cpu "
    sys.exit(1)
  #zabbix
  globalhost,db,dbuser,dbpasswd,api,zbuser,zbpasswd
  conf=ConfigParser.ConfigParser()
  conf.read('screen.ini')
  host=conf.get("zabbix","host")
  db=conf.get("zabbix","db")
  dbuser=conf.get("zabbix","dbuser")
  dbpasswd=conf.get("zabbix","dbpasswd")
  zbuser=conf.get("zabbix","zbuser")
  zbpasswd=conf.get("zabbix","zbpasswd")
  api=conf.get("zabbix","api")
  authstr=GetAuthStr()
  #print authstr
  #  itm=sys.argv[1].upper()
  #idc=sys.argv[3].upper()
  #screen_name=domain+'('+itm+')'
  #print screen_name
  #aph name
  items={}
  tmpstr=''
  fhandle=open('item.ini','r')
  confinfo=fhandle.readlines()
  for iline in confinfo:
    tmpstr+=iline
  #print tmpstr
  #json
        items=json.loads(tmpstr)
  item=items[itm]
  #print "item:"+item
  hconf=ConfigParser.ConfigParser()
  hconf.read('host.ini')
  names=hconf.sections()
  for domain in names:#    screenitem=''
    x=y=0
    screenid=GetScreenId()
    #print"screenid:"+str(screenid)
    screen_name=domain+'('+itm+')'
    hosts=hconf.get(domain,"host").split(',')
    for ip in hosts:
      if x>1:
        x=0
        y=y+1
      #print ip
      resourceid=GetResourceId(item,ip)
      #print"resourceid:"+str(resourceid)
      screenitem=screenitem+GetScreeItems(screenid,resourceid,x,y)+','
      x=x+1
    #
    screenitem=screenitem.strip(',')
    #print screenitem
    vsize=y+1
    cmdstr='''curl -i -s -X POST -H'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"screen.create","params": {"name":"'''+screen_name+'''","hsize":2,"vsize":'''+str(vsize)+''',"screenitems":['''+screenitem+''']},"auth":"'''+authstr+'''","id": 1}' '''+api
    print cmdstr
    os.system(cmdstr)

2.5接口程序:addscreen.sh

#!/bin/sh
#cpu
python screen.py cpu
#mem
python screen.py mem
#
python screen.py disk
#traffic
python screen.py traffic
#tcp udp
python screen.py tcp
#windows swap
#python screen.py swap

2.6执行

sh addscreen.sh

三、批量添加主机

3.1配置文件:config.ini

[config]
db=monitor
user=monitor
passwd=monitor
dbtab=zabbix_dbconf
host=192.168.122.103
[zabbix]
db=zabbix
user=zabbix
passwd=zabbix
zb_user=Admin
zb_passwd=zabbix
[graph_idc2]
zbserver=192.168.122.100
dbport=3306
zburl=http://192.168.122.100/api_jsonrpc.php
zbagent=192.168.122.101

3.2主程序:daemon_config_host.sh

#!/bin/bash
#invoking config_host.sh
host_dbname='monitor'
host_dbuser='monitor'
host_dbpasswd='monitor'
host_dbport=3306
host_dbhost='192.168.122.103'
dbconn="mysql-u${host_dbuser} -p${host_dbpasswd} -h${host_dbhost} -P${host_dbport} ${host_dbname}"
help(){
 echo "$0 [target] [action] {group}"
 echo "target:"
 echo " client ip"
 echo "action:"
 echo " create|delete"
 echo "group:"
 echo " [dns|lvs|haproxy|tengine|other]"
 echo "---*---"
 echo "if action=create,then you shouldput a group"
 echo "exp:"
 echo " $0 110.110.110.110 create lvs"
 echo " $0 110.110.110.110 delete"
 exit 0
}
get_config_ini(){
#get the config.ini from10.64.5.17
 #wget the new one.
 cd /tmp && wget -qchttp://10.64.5.14/tech/zabbix_hostconf/config.ini
 #if md5 not same,rm local file.
 md5_old=`md5sum/usr/local/zabbix/script/config.ini|awk '{print $1}'`
 md5_new=`md5sum /tmp/config.ini|awk '{print$1}'`
 if [ "${md5_old}" = "${md5_new}"]
 then
  echo "config.ini is not change."
 else
  rm -rf /usr/local/zabbix/script/config.ini&& mv /tmp/config.ini /usr/local/zabbix/script/config.ini
 fi
}
check_host(){
#check the host exist.
 check_result=`curl -s -X POST -H"Content-Type: application/json" -d '{"jsonrpc":"2.0","method": "host.exists","params":{"host": '\"${client_ip}\"',"nodeids":["0"]},"auth": '\"${auth_passwd}\"',"id":0}' ${api_url##*=}|awk -F, '{print $2}'|awk -F: '{if(NF==2) {print $2}}'`
}
create_host(){
 if [ "${check_result}" ="false" ]
 then
  #to create host.
  if [ "aa${linux_template_id}aa"!= "aa${template_id}aa" ]
  then
   curl -s -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"host.create","params": {"host":'\"${client_ip}\"',"interfaces":[{"type": 1,"main": 1,"useip":1,"ip":'\"${client_ip}\"',"dns":"","port": "10050"}],"groups": [{"groupid":'\"${group_id}\"'}],"templates":[{"templateid":'\"${linux_template_id}\"'},{"templateid":'\"${template_id}\"'}]},"auth":'\"${auth_passwd}\"',"id":0}' ${api_url##*=}
  else
   curl -s -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"host.create","params":{"host":'\"${client_ip}\"',"interfaces":[{"type": 1,"main": 1,"useip":1,"ip":'\"${client_ip}\"',"dns":"","port": "10050"}],"groups":[{"groupid":'\"${group_id}\"'}],"templates":[{"templateid":'\"${linux_template_id}\"'}]},"auth":'\"${auth_passwd}\"',"id":0}' ${api_url##*=}
  fi
 else
  echo "${client_ip} is exist."
 fi
}
delete_host(){
 if [ "${check_result}" ="true" ]
 then
  host_id=`${zabbix_db_conn} -e "selecthostid from hosts where host=\"${client_ip}\""|grep -v 'hostid'`
  #to delete host.
  curl -s -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"host.delete","params": [{"hostid":'\"${host_id}\"'}],"auth":'\"${auth_passwd}\"',"id":0}' ${api_url##*=}
 else
  echo "${client_ip} is not exist."
 fi
}
config_host(){
#get zabbix conn fromconfig.ini
CONFIG_INI="/usr/local/zabbix/script/config.ini"
#get some var.
username=`awk -F\= '{if($1~/\[zabbix\]/){getline;getline;getline;getline;print $0}}' ${CONFIG_INI}`
passwd=`awk -F\= '{if($1~/\[zabbix\]/){getline;getline;getline;getline;getline;print $0}}'${CONFIG_INI}`
db_name=`awk -F\= '{if($1~/\[zabbix\]/){getline;print $0;getline;print $0;getline;print $0}}'${CONFIG_INI}|grep -w 'db'`
db_user=`awk -F\= '{if($1~/\[zabbix\]/){getline;print $0;getline;print $0;getline;print $0}}'${CONFIG_INI}|grep -w 'user'`
db_passwd=`awk -F\= '{if($1~/\[zabbix\]/){getline;print $0;getline;print $0;getline;print $0}}'${CONFIG_INI}|grep -w 'passwd'`
if [[ $# < 2 ]] || [[ $#> 3 ]]
then
 help
fi
client_ip=$1
case $2 in
create)
 case $3 in
 dns)
  group_name='dns'
 ;;
 lvs)
  group_name='lvs'
 ;;
 haproxy)
  group_name='haproxy'
 ;;
 tengine)
  group_name='tengine'
 ;;
 other)
  group_name='linux'
 ;;
 esac
 for z_server in `awk -F\= '{if($1~/zbserver/)print $2}' ${CONFIG_INI}`
 do
  #get the linux template id.
  db_port=`awk -F\=-vz_s="${z_server}" '{if ($2==z_s){getline;print $0}}' ${CONFIG_INI}`
  zabbix_db_conn="/usr/bin/mysql-u${db_user##*=} -p${db_passwd##*=} -h${z_server} -P${db_port##*=}${db_name##*=}"
  linux_template_id=`${zabbix_db_conn} -e"select hostid from hosts where name=\"linux\""|grep -v'hostid'`
  api_url=`awk -F\=-vz_s="${z_server}" '{if ($2==z_s){getline;getline;print $0}}'${CONFIG_INI}`
  group_id=`${zabbix_db_conn} -e "selectgroupid from groups where name=\"${group_name}\""|grep -v'groupid'`
  template_id=`${zabbix_db_conn} -e"select hostid from hosts wherename=\"${group_name}\""|grep -v 'hostid'`
  #to get the auth.
  auth_passwd=`curl -s -X POST -H"Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"user.login","params":{"user":'\"${username##*=}\"',"password":'\"${passwd##*=}\"'},"auth":null,"id":0}' ${api_url##*=}|awk -F\" '{print $8}'|grep -v ^$`
  check_host
  create_host
 done
  ${dbconn} -e "update zabbix_hostconfset stat=0 where ip='${c_ip}'" && echo "${c_ip} createmonitor ok,and set stat to 0."
;;
delete)
 for z_server in `awk -F\= '{if($1~/zbserver/)print $2}' ${CONFIG_INI}`
 do
  #getthe linux template id.
  db_port=`awk -F\=-vz_s="${z_server}" '{if ($2==z_s){getline;print $0}}' ${CONFIG_INI}`
  zabbix_db_conn="/usr/bin/mysql-u${db_user##*=} -p${db_passwd##*=} -h${z_server} -P${db_port##*=}${db_name##*=}"
  linux_template_id=`${zabbix_db_conn} -e"select hostid from hosts where name=\"linux\""|grep -v'hostid'`
  api_url=`awk -F\=-vz_s="${z_server}" '{if ($2==z_s){getline;getline;print $0}}'${CONFIG_INI}`
  #to get the auth.
  auth_passwd=`curl -s -X POST -H "Content-Type:application/json" -d '{"jsonrpc":"2.0","method":"user.login","params":{"user":'\"${username##*=}\"',"password":'\"${passwd##*=}\"'},"auth":null,"id":0}' ${api_url##*=}|awk -F\" '{print $8}'|grep -v ^$`
  check_host
  delete_host
 done
  ${dbconn} -e "delete from zabbix_hostconfwhere ip='${d_ip}'" && echo "${d_ip} delete monitor ok."
;;
*)
 help
esac
}
get_config_ini
#get the ip list of create.
create_list=`${dbconn} -e"select ip from zabbix_hostconf where stat=1"`
if [ "aa" ="a${create_list}a" ]
then
 echo "no ip need create monitor."
else
 for c_ip in ${create_list##*ip}
 do
  c_ip_group_=`${dbconn} -e "selecthostgroup from zabbix_hostconf where ip='${c_ip}'"`
  c_ip_group=${c_ip_group_##*hostgroup}
  config_host ${c_ip} create ${c_ip_group}
 done
fi
#get the ip list of delete.
delete_list=`${dbconn} -e"select ip from zabbix_hostconf where stat=2"`
if [ "aa" ="a${delete_list}a" ]
then
 echo "no ip need delete monitor."
else
 for d_ip in ${delete_list##*ip}
 do
  config_host ${d_ip} delete
 done
fi

3.3中间状态表结构:

可忽略