本文配置步驟:
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 -*-
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)
