美文网首页zabbix
zabbix4.0通过python脚本发企业微信告警

zabbix4.0通过python脚本发企业微信告警

作者: 肆無忌惮 | 来源:发表于2020-06-17 00:11 被阅读0次

    python脚本为敏捷开发脚本,在zabbix监控也起到重要作用,以下是使用python脚本发送企业微信告警的配置方法。

    脚本如下:

    #!/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":"WeiZhiGang",   #企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
            "toparty":"2",        #企业号中的部门id。
            "msgtype":"text",     #消息类型。
            "agentid":"1000002",  #企业号中的应用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 =  'xxxxxxxxxxx'                     #企业号的标识
        corpsecret = 'xxxxxxxxxxxxxxxxxxxxxxxxx'    #应用管理密钥
        accesstoken = gettoken(corpid,corpsecret)
        senddata(accesstoken,user,subject,content)
    

    新建weixin.py文件,将以上代码复制编辑,修改里面用户账号,部门id,消息类型,应用id,企业id,应用密钥。
    保存后输入chmod a+x weixin.py 给weixin.py文件赋予执行权
    在zabbix客户端创建一个告警媒介


    微信截图_20200617000421.png

    修改用户的告警媒介,用户的媒介中的收件人,写微信组里面的账号,如果错误则发给组内全部人。


    微信截图_20200617000449.png
    还有配置-动作中的配置也要改为微信告警。 微信截图_20200617000534.png
    微信截图_20200617000545.png

    如果收不到信息,报缺少simplejson,则安装

    yum install -y phthon-simplejson
    

    相关文章

      网友评论

        本文标题:zabbix4.0通过python脚本发企业微信告警

        本文链接:https://www.haomeiwen.com/subject/ngodxktx.html