zabbix python 微信告警脚本
测试zabbix的微信告警耗费了大量时间,使用了开源工具(OneOaaS weixin-alert)、shell脚本工具(手动执行正常,服务器调用失败),均没有实现相关功能
以下是自己优化过的Python脚本
Python大法好!!
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib,urllib2,json import sys reload(sys) sys.setdefaultencoding( "utf-8" ) class WeChat(object): __token_id = '' # init attribute def __init__(self,url): self.__url = url.rstrip('/') self.__corpid = 'wx80179d3a3eb675c2' self.__secret = 'rf8zW7iF-VECQVwKGndrHzAkEqfcnmSXmhIGUHCKH24' # Get TokenID def authID(self): params = {'corpid':self.__corpid, 'corpsecret':self.__secret} data = urllib.urlencode(params) content = self.getToken(data) try: self.__token_id = content['access_token'] # print content['access_token'] except KeyError: raise KeyError # Establish a connection def getToken(self,data,url_prefix='/'): url = self.__url + url_prefix + 'gettoken?' try: response = urllib2.Request(url + data) except KeyError: raise KeyError result = urllib2.urlopen(response) content = json.loads(result.read()) return content # Get sendmessage url def postData(self,data,url_prefix='/'): url = self.__url + url_prefix + 'message/send?access_token=%s' % self.__token_id request = urllib2.Request(url,data) try: result = urllib2.urlopen(request) except urllib2.HTTPError as e: if hasattr(e,'reason'): print 'reason',e.reason elif hasattr(e,'code'): print 'code',e.code return 0 else: content = json.loads(result.read()) result.close() return content # send message def sendMessage(self,touser,subject,message): self.authID() data = json.dumps({ 'touser':touser, 'msgtype':"news", 'agentid':"1", 'news':{ "articles":[ { "title": subject, "description":message, } ] }, }) response = self.postData(data) print response if __name__ == '__main__': a = WeChat('https://qyapi.weixin.qq.com/cgi-bin') a.sendMessage(sys.argv[1],sys.argv[2],sys.argv[3])
微信发消息接口:
http://qydev.weixin.qq.com/wiki/index.php
脚本使用方法:
python weixin.py userID title content
发送给所有用户:
python weixin.py @all title content
zabbix配置微信告警
管理→报警媒介类型→创建媒体类型
需添加的参数:
{ALERT.SENDTO}
{ALERT.SUBJECT}
{ALERT.MESSAGE}
配置→动作→(触发器)创建动作
默认操作步骤持续时间设置为60s
[FAIL]: {EVENT.TIME}: {TRIGGER.NAME}
主机: {HOST.NAME1}
状态: {TRIGGER.STATUS}
级别: {TRIGGER.SEVERITY}
name: {ITEM.NAME1}
key: {ITEM.KEY1}
最后值: {ITEM.VALUE1}
[OK]-{EVENT.RECOVERY.TIME}: {TRIGGER.NAME}
主机: {HOST.NAME1}
状态: {TRIGGER.STATUS}
级别: {TRIGGER.SEVERITY}
name: {ITEM.NAME1}
key: {ITEM.KEY1}
最后值: {ITEM.VALUE1}
动作执行的操作配置
用户配置
微信告警效果图:
邮件告警zabbix配置
Learn how to learn~~