fairyguo 发表于 2018-8-5 08:55:58

zabbix使用微信报警python脚本

#!/usr/bin/python3  
# coding: utf-8
  
#python3将zabbix报警信息发送到微信。
  
#by http://sunday208.blog.51cto.com/ #2016-01-18
  
import urllib.request
  
import json
  
import sys
  

  
def gettoken(corp_id,corp_secret):
  
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corp_id + '&corpsecret=' + corp_secret
  
    try:
  
      token_file = urllib.request.urlopen(gettoken_url)
  
    except urllib.error.HTTPError as e:
  
      print(e.code)
  
      print(e.read().decode("utf8"))
  
    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,content):
  
    try:
  
      send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
  
      send_values = {
  
            "touser":user,#企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
  
            "toparty":"1",#企业号中的部门id
  
            "msgtype":"text",
  
            "agentid":"1",   #企业号中的应用id,消息类型。
  
            "text":{
  
                "content":content
  
                },
  
            "safe":"0"
  
            }
  
      send_data = json.dumps(send_values, ensure_ascii=False).encode(encoding='UTF8')
  
      send_request = urllib.request.Request(send_url, send_data)
  
      response = urllib.request.urlopen(send_request)
  
      msg = response.read()
  
      print("returned value : " + str(msg))
  
    except:
  
      print("returned value : " + str(msg))
  

  
default_encoding = 'utf-8'
  
if sys.getdefaultencoding() != default_encoding:
  
    reload(sys)
  
    sys.setdefaultencoding(default_encoding)
  
user = str(sys.argv)   #zabbix传过来的第一个参数
  
content = str(sys.argv)#zabbix传过来的第三个参数
  
corpid = 'XXXX'   #CorpID是企业号的标识
  
corpsecret = 'XXXXX'#corpsecretSecret是管理组凭证密钥
  
accesstoken = gettoken(corpid,corpsecret)
  
senddata(accesstoken,user,content)
页: [1]
查看完整版本: zabbix使用微信报警python脚本