【微信告警脚本】python3企业微信告

发布时间:2019-09-25 08:13:22编辑:auto阅读(1575)

    #!/usr/bin/python
    # --*-- encoding=utf-8 --*--
    
    import urllib.request
    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 = urllib.request.urlopen(gettoken_url)
        except urllib.request.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(content,accesstoken):
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken
        send_values = {
            "touser": '@all',  # 企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。@all 发送所有人
            #"touser": "HX0011055|HX0011027",  # 企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
            #"touser": "HX0010933",  # 企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
            #"touser": "HX0011055",  # 企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
            "toparty": "1",  # 企业号中的部门id。
            "msgtype": "text",  # 消息类型。
            "agentid": "1000003",  # 企业号中的应用id。
            "text": {
                "content": content
            },
            "safe": "0"
        }
        send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
        send_request = urllib.request.Request(send_url, send_data)
        response = json.loads(urllib.request.urlopen(send_request).read())
        print(str(response))
    
    def deal(content):
        corpid = 'ww861ef6bad293d02311'  # CorpID是企业号的标识
        corpsecret = 'Pn3YA4H0d87He8ef-hpf0tGB5HzYUvsEtoLwUKsAHWott'  # corpsecretSecret是管理组凭证密钥
        accesstoken = gettoken(corpid, corpsecret)
        senddata(content,accesstoken)
    
    #通过deal 函数直接发送信息
    message = '测试'
    deal(message)

关键字