本文配置步骤:
https://work.weixin.qq.com/api/doc#10013
第一个要记录的值:部门ID:1
选择企业应用
选择创建应用
自定义填
创建应用后退出,点击刚才创建的应用进入
记录下这两个值:AgentId、Secret
然后选择企业
记录值:CorpId
可以使用企业微信的API接口测试一下
http://work.weixin.qq.com/api/devtools/devtool.php
返回值如下即为OK,可以写脚本引用
告警脚本:(此脚本针对部门ID发送,添加后台应用选择哪些人可见然后哪些人就可以收到告警了,如果新增一个应用,就copy这个代码到另一个脚本修改corpid就可以了)
#!/usr/bin/env python # -*- coding: utf-8 -*- # auth: __ linda __ 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 = ‘xxx‘ #这里修改企业id self.__secret = ‘xxx-xxx‘ #这里修改告警应用secretid # 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({ ‘totag‘:touser, ‘msgtype‘:"text", ‘agentid‘:"2", ##这里修改告警应用id ‘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])
测试发送:python zabbix_weixin.py "1" "test" "test"
测试没有问题,开始配置zabbix
选择创建用户
添加报警媒介
权限可以看情况分配,我这自己用可以给大一点
选择报警媒介类型
创建媒体类型 别忘点“更新”
选择配置-动作
创建动作
默认接收人:
告警 {TRIGGER.NAME} 时间: {EVENT.DATE} {EVENT.TIME} 内容: 1. {ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): {ITEM.VALUE1}
Recovery operations
默认接收人:
恢复 {TRIGGER.NAME} 时间: {EVENT.RECOVERY.DATE} {EVENT.RECOVERY.TIME} 内容: 1. {ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): {ITEM.VALUE1}
将zabbix_server的agent关闭看是否报警,然后再启动看是否有恢复通知
钉钉告警一样,下载千思网 的钉钉告警脚本。拉钉钉群聊,添加机器人记录地址
https://www.qiansw.com/golang-zabbix-alter-to-dingding.html
告警xml内容
<?xml version="1.0" encoding="UTF-8" ?><root> <from>{HOSTNAME1}</from> <time>{EVENT.DATE} {EVENT.TIME}</time> <name>{TRIGGER.NAME}</name> <key>{TRIGGER.KEY1}</key> <value>{ITEM.VALUE}</value> <now>{ITEM.LASTVALUE}</now> <id>{EVENT.ID}</id> <ip>{HOST.IP}</ip> <url>这里是点击报警消息可以访问的链接地址</url> <age>{EVENT.AGE}</age> <status>{EVENT.STATUS}</status> <acknowledgement> {EVENT.ACK.STATUS} </acknowledgement><acknowledgementhistory> {EVENT.ACK.HISTORY}</acknowledgementhistory></root>
恢复内容
{TRIGGER.STATUS}: {TRIGGER.NAME} <?xml version="1.0" encoding="UTF-8" ?><root> <from>{HOSTNAME1}</from> <time>{EVENT.DATE} {EVENT.TIME}</time> <name>{TRIGGER.NAME}</name> <key>{TRIGGER.KEY1}</key> <value>{ITEM.VALUE}</value> <now>{ITEM.LASTVALUE}</now> <id>{EVENT.ID}</id> <ip>{HOST.IP}</ip> <color>FF4A934A</color> <url>这里的url会替换报警媒介的url</url> <age>{EVENT.AGE}</age> <recoveryTime>{EVENT.RECOVERY.DATE} {EVENT.RECOVERY.TIME}</recoveryTime> <status>{EVENT.RECOVERY.STATUS}</status> </root>
其他调用钉钉机器人告警
#conding=utf-8 ## -- coding:UTF-8 -- import requests import json import time,datetime import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def sendmail(subject,msg,toaddrs,fromaddr,smtpaddr,password): mail_msg = MIMEMultipart() if not isinstance(subject,unicode): subject = unicode(subject, ‘utf-8‘) mail_msg[‘Subject‘] = subject mail_msg[‘From‘] = fromaddr mail_msg[‘To‘] = ‘,‘.join(toaddrs) mail_msg.attach(MIMEText(msg, ‘html‘, ‘utf-8‘)) try: s = smtplib.SMTP() s.connect(smtpaddr) #连接smtp服务器 s.login(fromaddr,password) #登录邮箱 s.sendmail(fromaddr, toaddrs, mail_msg.as_string()) #发送邮件 s.quit() except Exception,e: print "Error: unable to send email" def msg(text): json_text = { "msgtype": "text", "at": { "atMobiles": [ "11111" ], "isAtAll": False }, "text": { "content": text } } print(requests.post(api_url, json.dumps(json_text), headers=headers).content) if __name__ == ‘__main__‘: ‘‘‘ https://oapi.dingtalk.com/robot/send?access_token=xxx ‘‘‘ #钉钉发送 #token = "xxx" token = "xxx" date = datetime.datetime.now().strftime(‘%Y-%m‘) text = "xxx" % date headers = {‘Content-Type‘: ‘application/json;charset=utf-8‘} api_url = "https://oapi.dingtalk.com/robot/send?access_token=%s" % token msg(text)