zabbix4.0 微信監控報警腳本

[root@localhost alertscripts]# cat weixin.py
#!/usr/bin/python
#_*_coding:utf-8 _*_


import urllib,urllib2
import json
import sys
import simplejson

reload(sys)
sys.setdefaultencoding('utf-8')


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":"weixin",         #企業號中的用戶帳號,在zabbix用戶Media中配置,如果配置不正常,將按部門發送。
        "toparty":"3",                 #企業號中的部門id。
        "msgtype":"text",          #消息類型。
        "agentid":"9999999",  #企業號中的應用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 =  '9999999'           #企業號的標識 
    corpsecret = '9999999'    #管理組憑證密鑰 
    accesstoken = gettoken(corpid,corpsecret)
    senddata(accesstoken,user,subject,content)

 

 

測試方法:

#cd /usr/lib/zabbix/alertscripts

#./weixin.py username test test
 

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