#!/usr/bin/python
#-*- coding: UTF-8 -*-#Function: 微信报警python版(带波动图)
#Environment: python2.7.6import urllib2,chardet
import sys,json,re
def 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 inzabbix_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.reasonelse:
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()