Zabbix使用手册:实现微信告警

微信作为一个最为频繁的沟通工具,如今还被用作Zabbix的告警途径,本文讲述如何通过微信企业号中发送消息的能力实现Zabbix告警通知。

0x01 配置微信应用

首先,点击此处注册企业微信,一般用户均可注册,无需验证企业信息,输入企业信息和管理员信息,用管理员微信扫码后即可注册。

然后,维护需要通过微信接收告警信息的联系人,后期可以随时维护。

最后,进入“应用管理”频道,自建一个应用,配置接收告警信息的成员或组。

重要提示:应用的“可见范围”若按添加,则告警信息将发送给当前用户所在组的所有成员

0x02 配置微信告警脚本

编写信息发送脚本/usr/lib/zabbix/alertscripts/zabbixWX.py

#!/usr/bin/python
# _*_ coding:utf-8 _*_

import urllib,urllib2
import json
import sys
import simplejson

reload(sys)
# 在python3中无需转码
sys.setdefaultencoding('utf-8')

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,user,subject,content):
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
        "touser":user,        #企业号中的用户帐号,在zabbix用户Media中配置,配置有误时将按部门发送
        "toparty":"2",        #企业号中的部门ID,在通讯录中的部门菜单
        "msgtype":"text",     #消息类型
        "agentid":"1000002",  #企业号中应用的AgentId,在应用信息页面
        "text":{
            "content":subject + '\n' + content
        },
        "safe":"0"
    }
    # 在python3中无需转码
    # send_data = simplejson.dumps(send_values, ensure_ascii=False)
    send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
    print(send_data)
    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 = 'ww****************' #企业号的标识CorpID,在企业信息页面
    corpsecret = '**************' #企业号中应用的Secret,在应用信息页面
    accesstoken = gettoken(corpid,corpsecret)
    senddata(accesstoken,user,subject,content)

配置脚本权限:

chmod +x /usr/lib/zabbix/alertscripts/zabbixWX.py
chown -R zabbix:zabbix /usr/lib/zabbix/alertscripts/zabbixWX.py

访问PyPI下载页面或者本地分享点下载并安装simplejson,本站提供的版本为3.17.2,解压并安装。

wget https://olzl.cn/oldwww/simplejson -O simplejson-3.17.2.tar.gz
tar zxvf simplejson-3.17.2.tar.gz
cd simplejson-3.17.2
python setup.py build
python setup.py install

测试是否可用:

python zabbixWX.py <user> 告警标题 详细内容

修改zabbix_server配置/etc/zabbix/zabbix_server.conf,完成后重启zabbix-server。

AlertScriptsPath=/usr/lib/zabbix/alertscripts

0x03 配置zabbix

登录Zabbix创建报警媒介类型,参数如下:

{ALERT.SENDTO}
{ALERT.SUBJECT}
{ALERT.MESSAGE}

随后依次配置用户报警媒介及报警动作,本文略。

原创文章禁止转载:技术学堂 » Zabbix使用手册:实现微信告警

精彩评论

4+7=

感谢您的支持与鼓励

支付宝扫一扫打赏

微信扫一扫打赏