cat /usr/local/zabbix/share/zabbix/alertscripts/sed_messages_weixin.py python2.x #!/usr/bin/env python # _*_ coding: utf-8 _*_ # author:chenjianwen # email:1071179133@qq.com import sys import urllib2 import json import requests toparty = sys.argv[1] #发给哪个部门 title = sys.argv[2] #标题 message = sys.argv[3] #内容 corpid = 'ww7xxxx' #企业微信号id #corpsecret = 'Hjekn1xxxV9xA' ##应用Secret if toparty == "4": #根据部门id确定对应项目的报警消息发送到对应部门 corpsecret = 'xxxxxxxxxxxxxxxxxxxxxxx' agentid = 1000004 elif toparty == "13": corpsecret = 'xxxxxxxxxxxxxxxxxxxxxxx' agentid = 1000013 get_access_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s'%(corpid,corpsecret) def get_access_token(get_access_token_url): data = urllib2.urlopen(get_access_token_url).read().decode('utf-8') data = json.loads(data) #print data["access_token"] return data["access_token"] def send_messages(access_token,toparty,agentid,content): send_messages_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s'%access_token data = { "touser" : "", #成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送 "toparty" : toparty, ##部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 "totag" : "", #标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 "msgtype" : "text", #消息类型,此时固定为:text "agentid" : agentid, #企业应用的id,整型。可在应用的设置页面查看 "text" : { "content" : content #消息内容,最长不超过2048个字节 }, "safe":0 #表示是否是保密消息,0表示否,1表示是,默认0 } value = json.dumps(data) ##转换为str格式 request = requests.post(send_messages_url, data=value) ##post请求发送数据 request_result = request.status_code ##获取请求码 if request_result == 200: print "【%s】消息发送成功"%content else: print "【%s】消息发送失败"%content if __name__ == '__main__': access_token = get_access_token(get_access_token_url) send_messages(access_token,toparty,agentid,message)