zabbix设置微信报警

zabbix支持多种报警机制,比如:邮件、短信、微信等等。下面就介绍如何使用微信报警。
使用微信报警必须得有企业微信账号,普通的微信账号不行。

申请企业微信

注册地址:https://work.weixin.qq.com/
注册企业微信,根据提示填写自己的信息就行,注册完成后会有提示进入管理后台。根据自己需要设置即可,由于已经注册过了具体步骤就不在演示。


需要记住的几个信息。
成员账号:添加的成员账号。
组织部门ID:可以在通讯录中部门右侧竖着的三个点处查看。
Agentid:企业应用中选中对应的应用点击进去后就可以看到。
Secret:跟Agentid在一起。
CorpID:我的企业里面可以查看。

zabbix配置

修改zabbix-server配置文件,指定报警脚本的位置,我的在/usr/lib/zabbix/alertscripts目录下。

# grep alertscripts /etc/zabbix/zabbix_server.conf
AlertScriptsPath=/usr/lib/zabbix/alertscripts

脚本配置

安装simplejson

# yum install python-simplejson -y

上传脚本,并根据注释修改成自己的信息。

#!/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":"XXX",    #企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。
        "toparty":"X",    #企业号中的部门id。
        "msgtype":"text", #消息类型。
        "agentid":"1000005",    #企业号中的应用id。
        "text":{
            "content":subject + '\n\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 = simplejson.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 =  '1111111111111111'   #CorpID是企业号的标识
    corpsecret = '111111111111111111111111'  #corpsecretSecret是管理组凭证密钥
    accesstoken = gettoken(corpid,corpsecret)
    senddata(accesstoken,user,subject,content)

可以做测试,看看能否发出信息

# python wechat_alert.py test test test
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwe302dd7e2757ca1c&corpsecret=o5W2pH9Bo4nOtJBi8yNzPeQ2j-T7KypPcRJ8Hu_E0HU
{'invalidparty': '2', 'invaliduser': u'', 'errcode': 0, 'errmsg': 'ok'}


证明能够正常收到消息。

猜你喜欢

转载自www.cnblogs.com/ebay/p/8963500.html