Centos7下zabbix部署(五)定义报警媒介-微信
1.注册微信
注册过程参考地址:https://www.cnblogs.com/hanyifeng/p/5368102.html
主要需要以下一些信息
CorpID : wwxxxxxxxxxxxx99d
AgentId: 1000004
Secret: EQxxxxxxxxxxxxxxxxxxxxxxxxxxxMVkuUm3U
部门ID: 2
2.编写服务端发送微信的脚本
[root@zabbix-server alertscripts]# cat weixin.py #!/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 = 'wwxxxxxxxxxxxx9d' #需要改 self.__secret = 'EQxxxxxxxxxxxxxxxxxxxxxMVkuUm3U' #需要改 # 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,message): self.authID() data = json.dumps({ 'touser':touser, 'toparty':"2", #需要改(部门id) 'msgtype':"text", 'agentid':"1000004", #需要改 'text':{ 'content':message }, 'safe':"0" },ensure_ascii=False) 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[3])
3.给脚本授权更改属性,并测试
[root@zabbix-server alertscripts]# chmod +x weixin.py
[root@zabbix-server alertscripts]# chown zabbix.zabbix weixin.py
[root@zabbix-server alertscripts]# ./weixin.py YangHaiLong test test
# 测试出现ok字样表示成功你的企业微信应该可以收到test的信息
[root@zabbix-server alertscripts]# ./weixin.py YangHaiLong test test {u'invaliduser': u'', u'errcode': 0, u'errmsg': u'ok'}
4.在zabbix网页设置报警媒介和动作
我这个动作只设了一个触发器的动作,监控80端口是否存在,不存在触发报警,执行动作,动作就是执行这个weixin.py脚本发送报警信息。
我关掉nginx服务 80端口消失,触发报警
[root@zabbix-agent ~]# netstat -lntup|grep 80 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 20430/nginx: master tcp6 0 0 :::80 :::* LISTEN 20430/nginx: master
[root@zabbix-agent ~]# systemctl stop nginx
[root@zabbix-agent ~]# netstat -lntup|grep 80
[root@zabbix-agent ~]#
网页上的日志成功的。
我同时设置了恢复后的报警。
[root@zabbix-agent ~]# systemctl start nginx [root@zabbix-agent ~]# netstat -lntup|grep 80 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 23737/nginx: master tcp6 0 0 :::80 :::* LISTEN 23737/nginx: master
ok 啦。