zabbx用微信接收告警

之前一直用的是短信接收zabbix告警。前两天刚好空了下来,研究了下微信接收zabbix短信。

1,https://mp.weixin.qq.com/ 注册微信账号

2,通讯录添加部门和成员,如下图,记住部门的ID号 我这里是1


3, 在菜单应用中心》新建应用》选择消息型应用



4填完后大概是下图


5 在设置>权限管理>新建管理组,填完大概是下图红色部分要记住。


5.微信接口调用

调用微信接口需要一个调用接口的凭证:access_token

通过CorpID和Secret可以获得access_token

微信企业号接口调试地址: http://qydev.weixin.qq.com/debug

红色部分填写上图红色部分


6,python脚本

#安装simplejson

wget https://pypi.python.org/packages/f0/07/26b519e6ebb03c2a74989f7571e6ae6b82e9d7d81b8de6fcdbfc643c7b58/simplejson-3.8.2.tar.gz
tar zxvf simplejson-3.8.2.tar.gz && cd simplejson-3.8.2
python setup.py build
python setup.py install
#下载wechat.py脚本

git clone https://github.com/X-Mars/Zabbix-Alert-WeChat.git
cp Zabbix-Alert-WeChat/wechat.py /opt/zabbix/share/zabbix/alertscripts/
chmod +x wechat.py && chown zabbix:zabbix wechat.py

7,

#修改脚本
#!/usr/bin/python
#_*_coding:utf-8 _*_
 
import urllib,urllib2
import json
import sys
import simplejson
 
def gettoken(corpid,corpsecret):
gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
print  gettoken_url
try:
token_file = urllib2.urlopen(gettoken_url)
except urllib2.HTTPError as e:
print e.code
print e.read().decode("utf8")
sys.exit()
token_data = token_file.read().decode('utf-8')
token_json = json.loads(token_data)
token_json.keys()
token = token_json['access_token']
return token
 
def senddata(access_token,user,subject,content):
 
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
send_values = {
"touser":"touser",      #企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。  #这行可要也可以不用要
"toparty":"2",          #企业号中的部门id。
"msgtype":"text",       #消息类型。
"agentid":"3",         #企业号中的应用id。
"text":{
"content":subject + '\n' + content
},
"safe":"0"
}
#    send_data = json.dumps(send_values, ensure_ascii=False)
send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
send_request = urllib2.Request(send_url, send_data)
response = json.loads(urllib2.urlopen(send_request).read())
print str(response)
 
if __name__ == '__main__':
user = str(sys.argv[1])     #zabbix传过来的第一个参数
subject = str(sys.argv[2])  #zabbix传过来的第二个参数
content = str(sys.argv[3])  #zabbix传过来的第三个参数
 
corpid =  'xxxxxx'   #CorpID是企业号的标识
corpsecret = 'M3FMhnFh8nTI6SxLAEbbLLZaj-1BpZIyqkJRskeMMUXObGx4mfQsAg7Jw-nUMXe9'    #Secret是管理组凭证密钥
accesstoken = gettoken(corpid,corpsecret)
senddata(accesstoken,user,subject,content)

8.测试

[root@zabbix alertscripts]# ./wechat.py   zhou  test   hello1
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=182c32ed&corpsecret=3pnUYeuCnP-wTOY0Ey
{u'errcode': 0, u'errmsg': u'ok'}
[root@zabbix alertscripts]# 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章