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]# 



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