zabbix使用python脚本给企业微信发送信息

wwechat.py

#!/usr/bin/python
# coding:utf-8
# 2016-01-18
import urllib, urllib2
import json
import sys
import logging
import subprocess
reload(sys)
sys.setdefaultencoding('utf8')
logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='/home/zabbix/wechat.log',
                filemode='w')
def gettoken(corpid, corpsecret):
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
    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,content):
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
#        "touser": user,  # 企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
        "toparty": party_ID,  # 企业号中的部门id
        "msgtype": "text",  # 企业号中的应用id,消息类型。
        "agentid": AgentId, #企业微信中添加报警中的AgentId
        "text": {
            "content": content
        },
        "safe": "0"
    }
    send_data = json.dumps(send_values, ensure_ascii=False)
    send_request = urllib2.Request(send_url, send_data)
    response = json.loads(urllib2.urlopen(send_request).read())
    logging.info(response)
     

if __name__ == '__main__':
#    user = sys.argv[1]     # zabbix传过来的第一个参数接受短信的部门
    party_ID = sys.argv[1]     # zabbix传过来的第一个参数接受短信的部门
    content = sys.argv[3]  # zabbix传过来的第三个参数接收的报警信息

    AgentId = sys.argv[4]     # 企业微信中添加报警中的AgentId
    corpsecret = sys.argv[5]  # corpsecretSecret是管理组凭证密钥
    corpid = '11111111111111111'  # CorpID是企业号的标识
    accesstoken = gettoken(corpid, corpsecret)
    senddata(accesstoken,content)
posted @ 2022-06-07 14:46  蒲公英PGY  阅读(87)  评论(0编辑  收藏  举报