#!/usr/bin/python# -*- coding: UTF-8 -*-#Function: 微信报警python版(带波动图)#Environment: python 2.7.6import urllib2,chardetimport sys,json,redef send_alter(): #发送报警到微信 AppID = ***** #应用ID UserID = ***** #用户ID,以|间隔可发送多人 PartyID = 1 #组ID GURL = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + CropID + '&corpsecret=' + Secret Request = urllib2.Request(GURL) Response = urllib2.urlopen(Request) access_token = eval(Response.read())['access_token'] PURL = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token data = { "touser" : UserID, "toparty": PartyID, "msgtype": "text", "agentid": AppID, "text": { "content": Msg }, "safe": 0 } encode_data = json.dumps(data, encoding='utf-8', ensure_ascii=False) #要将数据encode在json.dumps,不然微信无法识别 wx_req = urllib2.Request(PURL, encode_data) f = open('/home/zabbix/test','w') print >> f, urllib2.urlopen(wx_req).read()def get_return(data): request = urllib2.Request(zabbix_url + 'api_jsonrpc.php',data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) try: result = urllib2.urlopen(request) except HTTPError, e: print 'The server couldn\'t fulfill the request, Error code: ', e.code except URLError, e: print 'We failed to reach a server.Reason: ', e.reason else: response=json.loads(result.read()) return response result.close()def get_authcode(): #获取zabbix的auth_code auth_data = json.dumps( { "jsonrpc":"2.0", "method":"user.login", "params": { "user":zabbix_user, "password":zabbix_passwd }, "id":0 }) return get_return(auth_data)['result']def get_imgurl(): #获取监控项波动图片地址 ItemID = re.search('(告警监控项:.*\()(.*)(\))', sys.argv[1]).group(2) png_url = zabbix_url + "chart.php?period=3600&isNow=1&itemids%5B0%5D=" + ItemID + "&type=0&profileIdx=web.item.graph&profileIdx2=29123&width=1387" return png_urlif __name__ == '__main__': defaultencoding = 'utf-8' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) CropID='*******' #这两个要在微信企业号里找 Secret='********' #企业号里找 zabbix_url = 'http://****/zabbix/' #zabbix路径 new_details = '点击查看图片' Msg = re.sub('DETAILS', new_details, sys.argv[1]) send_alter()
推荐的动作格式:
产生告警!告警主机: {HOST.NAME}告警时间: {EVENT.DATE} 告警监控项: {ITEM.NAME}({ITEM.ID})告警触发器: {TRIGGER.NAME}告警状态: {TRIGGER.STATUS}告警级别: {TRIGGER.SEVERITY}告警详情: DETAILS监控项值:1.{ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}):{ITEM.VALUE1}2.{ITEM.NAME2} ({HOST.NAME2}:{ITEM.KEY2}):{ITEM.VALUE2}3.{ITEM.NAME3} ({HOST.NAME3}:{ITEM.KEY3}):{ITEM.VALUE3}事件 ID: {EVENT.ID} #推荐动作
接收到的信息:
点击查看图片会直接看到报警监控项的波动图(需要事先访问过该zabbix后台并留下cookie),如图: