人生不设限

导航

微信告警实现

zabbixversion:3.2.8

一、微信申请设置

1.注册企业微信
qy.weixin.qq.com
2.管理通讯录,添加成员
3.设置部门,分配成员
4.自定义企业应用,记录以下三个值
CorpID:
AgentId(应用id):
Secret:

5.调试接口
qydev.weixin.qq.com/debug

二、zabbix设置

1.编写微信发送信息脚本
测试
python sendwechat.py @all Sub_T "test the function of sendwechat"
python sendwechat.py 企业微信通讯录里的微信账号 T "test the function of sendwechat7"

#!/bin/env python
# -*- coding: UTF-8 -*-
import time
import urllib,urllib2
import json
import sys

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)

class WeChat():    
def __init__(self,touser,corpid,secret,content):
self.gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + secret 
def get_access_token(self,url):
try:    
token_file = urllib2.urlopen(url)    
except urllib2.HTTPError,e:
logFile = open('/tmp/zabbix.log','a')
print >>logFile,e.code
print >>logFile,e.read().decode("utf8")    
logFile.close()
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 send_messages(self,touser,content,access_token):
try: 
post_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
message_template = { 
"touser":touser,
"toparty":"1", 
"msgtype":"text", 
"agentid":"1", 
"text":{ 
"content":content 
}, 
"safe":"0" 
} 
main_messages = json.dumps(message_template, ensure_ascii=False,encoding='UTF8') 
request = urllib2.Request(post_url, main_messages) 
response = urllib2.urlopen(request)
msg = response.read()
except Exception,e:
logFile = open('/tmp/zabbix.log','a')
print >>logFile,e
logFile.close()
sys.exit()
return msg 
if __name__ == '__main__':
corpid = "申请企业微信号时会自动生成"
secret = "创建应用时会自动生成"
logFile = open('/tmp/zabbix.log','a')
try:
touser = sys.argv[1]
subject = sys.argv[2]
content = str(sys.argv[3])    
msg_sender = WeChat(touser,corpid,secret,content)
access_token = msg_sender.get_access_token(msg_sender.gettoken_url)    
print >>logFile, msg_sender.send_messages(touser,content,access_token) 
except Exception,e:
print >>logFile, e

2.web页面配置

 

 

 

 遇到的问题:

在配置完微信告警后,发现trigger无法触发action,日志里面也没有记录。追查原因发现,原来是scripts输出日志的属主是root,zabbix没有权限操作。修改为zabbix后成功发送微信告警。

 

 

 

posted on 2017-10-18 11:06  风的_理想  阅读(981)  评论(0编辑  收藏  举报