Zabbix微信报警脚本及写触发记录

时间:2019-08-10 19:25:48   收藏:0   阅读:112

一、Zabbix微信报警

默认路径:/usr/lib/zabbix/scripts/weixin.py

#!/usr/bin/python 
# -*- coding: utf-8 -*-

import urllib,json
import urllib2
import sys
import time
reload(sys)
#print sys.getdefaultencoding()
sys.setdefaultencoding(utf8)
#print sys.getdefaultencoding()
############################
#CorpId = ‘******9b5c9d******‘
#AgentId = ‘1000013‘
#Secret = ‘******7ln1_bRDLydnMBoCn9Cof7JqSiG7JuJ******‘
#AuthId = 60
############################
class WeChat(object):
        __token_id = ‘‘
        # init attribute
        def __init__(self,url):
                self.__url = url.rstrip(/)
                self.__corpid = ******9b5c9d******
                self.__secret = ******7ln1_bRDLydnMBoCn9Cof7JqSiG7JuJ******

        # Get TokenID
        def authID(self):
                params = {corpid:self.__corpid, corpsecret:self.__secret}
                data = urllib.urlencode(params)
                content = self.getToken(data)

                try:
                        self.__token_id = content[access_token]
                        #print(‘access_token: ‘+content[‘access_token‘])
                except KeyError:
                        raise KeyError

        # Establish a connection
        def getToken(self,data,url_prefix=/):
                url = self.__url + url_prefix + gettoken?
                try:
                        response = urllib2.Request(url + data)
                except KeyError:
                        raise KeyError
                result = urllib2.urlopen(response)
        #print(‘result: ‘,result)
                content = json.loads(result.read())
        #print(‘content: ‘,content)
                return content

        # Get sendmessage url
        def postData(self,data,url_prefix=/):
                url = self.__url + url_prefix + message/send?access_token=%s % self.__token_id
                request = urllib2.Request(url,data)
                try:
                        result = urllib2.urlopen(request)
                except urllib2.HTTPError as e:
                        if hasattr(e,reason):
                                print(reason,e.reason)
                        elif hasattr(e,code):
                                print(code,e.code)
                        return 0
                else:
                        content = json.loads(result.read())
                        result.close()
                return content

        # send message
        def sendMessage(self,touser,message):
                self.authID()
                data = json.dumps({
                        touser:touser,
                        toparty:"60",
                        msgtype:"text",
                        agentid:"1000013",
                        text:{
                                content:message
                        },
                        safe:"0"
                },ensure_ascii=False)

                response = self.postData(data)
                print(response)


if __name__ == __main__:
        a = WeChat(https://qyapi.weixin.qq.com/cgi-bin)
    f=open(r/tmp/wechat_warning.log, a+)
    for i in sys.argv:
            f.write(i)
        f.write("\n")
    f.close()
        a.sendMessage(sys.argv[1],sys.argv[3])

二、写触发事件日志

/usr/lib/zabbix/scripts/trigger.py

#!/usr/bin/python36
import sys,time
import pymysql

now=time.strftime(%Y-%m-%d %H:%M:%S,time.localtime())
f=open(r/tmp/trigger_writing.log, a+)
f.write("\n* * * * * * * * * * * * * * * * * * * * * * \n")
f.write(now+" ")
for line in sys.argv:
    f.write(line)
    f.write("\n")
f.write("\n")
f.close()

f=open(r/tmp/trigger_writing.log, a+)
print(sys.argv,file=f)
arr=sys.argv
need_arr =arr[3].split("\r\n")
for i in range(len(need_arr)):
    if i >= 0:
        key = need_arr[i].split(:)
        if key[0] == ip_addr:
            ip_addr = key[1].strip()
        elif key[0] == host_name:
            host_name = key[1].strip()
        elif key[0] == host_port:
            host_port = key[1].strip()
        elif key[0] == item_id:
            item_id = key[1].strip()
        elif key[0] == item_name:
            if len(key) > 2 :
                item_name = key[1].strip()+:+key[2].strip()
            else:
                item_name = key[1].strip()
        elif key[0] == item_key:
            if len(key) > 2:
                item_key = key[1].strip()+:+key[2].strip()
            else:
                item_key = key[1].strip()
        elif key[0] == item_value:
            item_value = key[1].strip()
        elif key[0] == item_lastvalue:
            item_lastvalue = key[1].strip()
        elif key[0] == trigger_id:
            trigger_id = key[1].strip()
        elif key[0] == trigger_name:
            if len(key) > 2:
                trigger_name = key[1].strip()+:+key[2].strip()
            else:
                trigger_name = key[1].strip()
        elif key[0] == trigger_severity:
            trigger_severity = key[1].strip()
        elif key[0] == trigger_status:
            trigger_status = key[1].strip()
        elif key[0] == trigger_value:
            trigger_value = key[1].strip()
        elif key[0] == event_age:
            event_age = key[1].strip()
        elif key[0] == event_date:
            event_date = key[1].strip()
        elif key[0] == event_time:
            event_time = key[1].strip()+:+key[2].strip()+:+key[3].strip()
        elif key[0] == event_id:
            event_id = key[1].strip()
        else:
            continue

value = ""+ip_addr+"‘,‘"+host_name+"‘,‘"+host_port+"‘,‘"+item_id+"‘,‘"+item_name+"‘,‘"        +item_key+"‘,‘"+item_value+"‘,‘"+item_lastvalue+"‘,‘"+trigger_id+"‘,‘"+trigger_name+"‘,‘"        +trigger_severity+"‘,‘"+trigger_status+"‘,‘"+trigger_value+"‘,‘"+event_age+"‘,‘"        +event_date+"‘,‘"+event_time+"‘,‘"+event_id+""

sql = "insert into sp_zbx_trigger (ipaddress,hostname,hostport,itemid,itemname,itemkey,itemvalue,itemlastvalue,triggerid,triggername,triggerseverity,triggerstatus,triggervalue,eventage,eventdate,eventtime,eventid) values " + "(" + value +")"
#print(sql,file=f)
f.write("\n"+sql+"\n")
f.close()

# conn database
db = pymysql.connect(host=192.168.0.201, port=3306, user=user, passwd=passwd, db=zabbix)
# create cursor
cursor = db.cursor()
try:
    if cursor.execute(sql):
        print(ok)
        db.commit()
except Exception as e:
        print(e.args)
        db.rollback()
db.close()

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!