前言
我们通常收到的报警,都是文字,是把动作中的消息内容当成了正文参数传给脚本,然后邮件或者微信进行接收,往往只能看到当前值,无法直观的获取到历史当天该监控项的运行曲线图,因此根据此需求,使用python编写脚本来分别对邮件告警和微信告警,进行升级,报警内容中加入了当天的历史趋势图,功夫不负有心人,已成功解锁,并实践成功,因此分享出来供大家参考。
指导
脚本代码
主要修改:
zabbix
zabbix连接
管理员账号
管理员密码
企业微信
企业ID
应用的Secret
#!/usr/bin/python
# encoding: utf-8
import sys
import requests
import json
import os
import time
import re
import logging
logging.basicConfig(level=logging.DEBUG,#控制台打印的日志级别
filename='/var/log/zabbix/wxwork_new.log',
filemode='a',##模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志
#a是追加模式,默认如果不写的话,就是追加模式
format=
'%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
#日志格式
)
zabbix_url = 'xxxxxxx'
url = 'http://'+zabbix_url+'/zabbix/api_jsonrpc.php'
headers = {'Content-Type': 'application/json-rpc'}
graph_path = '/data/zabbix/images/' # 定义图片存储路径
graph_url = 'http://'+zabbix_url+'/zabbix/chart.php' # 定义图表的url
loginurl = "http://'+zabbix_url+'/zabbix/index.php" # 定义登录的url
def uploadImg(path,accessToken):
#img_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=" + key + "&type=file"
img_url = "https://qyapi.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+accessToken
files = {'media': open(path, 'rb')}
r = requests.post(img_url, files=files)
re = json.loads(r.text)
print(re)
return re['url']
def get_itemid(message):
try:
print(message)
pattern = re.compile(ur'ITEMID:(\d+)')
itemid = pattern.search(message).group(1)
return itemid
except Exception as e:
return 0
def get_imgUrl(itemid):
session = requests.Session()
try:
loginheaders = {
"Host": zabbix_url,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
}
# 定义请求消息头
payload = {
"name": '管理员账号',
"password": '管理员密码',
"autologin": "1",
"enter": "Sign in",
}
# 定义传入的data
login = session.post(url=loginurl, headers=loginheaders, data=payload)
print(login)
graph_params = {
"from": "now-10m",
"to": "now",
"itemids[]": itemid,
"width": "400",
}
# 定义获取图片的参数
graph_req = session.get(url=graph_url, params=graph_params)
# 发送get请求获取图片数据
time_tag = time.strftime("%Y%m%d%H%M%S", time.localtime())
graph_name = 'baojing_' + time_tag + '.png'
# 用报警时间来作为图片名进行保存
graph_name = os.path.join(graph_path, graph_name)
# 使用绝对路径保存图片
with open(graph_name, 'wb', ) as f:
f.write(graph_req.content)
# 将获取到的图片数据写入到文件中去
return graph_name
except Exception as e:
print(e)
return False
def getAccessToken():
api_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=企业ID&corpsecret=应用的Secret"
content = requests.get(api_url)
#print(content.json())
return content.json().get("access_token")
def getImgUrl(mediaId,accessToken):
api_url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token="+accessToken+"&media_id="+mediaId
content = requests.get(api_url)
print(mediaId)
print(content.json())
return content.json().get("url")
def send_message(imgUrl,title,desc,openUrl,key):
# 发送消息
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key
# message = title # sys.argv[3]
params = {
"msgtype": "template_card",
"template_card": {
"card_type": "news_notice",
"source": {
"desc": "Zabbix网络警报",
"desc_color": 0
},
"vertical_content_list":{
"title": "详细信息",
"desc": desc
},
"main_title": {
"title": title
},
"card_image": {
"url": imgUrl
},
"card_action": {
"type": 1,
"url": openUrl,
"appid": "APPID",
"pagepath": "PAGEPATH"
}
}
}
logging.info(json.dumps(params));
req = requests.post(url, data=json.dumps(params))
print(req.json())
def send_message_text(title,desc,openUrl,key):
# 发送消息
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key
# message = title # sys.argv[3]
params = {
"msgtype": "template_card",
"template_card": {
"card_type": "text_notice",
"source": {
"desc": "Zabbix网络警报",
"desc_color": 0
},
"sub_title_text": desc,
"main_title": {
"title": title
},
"card_action": {
"type": 1,
"url": openUrl,
"appid": "APPID",
"pagepath": "PAGEPATH"
}
}
}
logging.info(json.dumps(params));
req = requests.post(url, data=json.dumps(params))
print(req.json())
if __name__ == '__main__':
message = sys.argv[2]
print(message)
itemid = get_itemid(message)
if itemid == 0:
send_message_text(sys.argv[1],sys.argv[2],"http://"+zabbix_url+"/zabbix/zabbix.php?action=dashboard.list",sys.argv[4])
else:
imgpath = get_imgUrl(itemid)
accessToken = getAccessToken();
imgUrl = uploadImg(imgpath,accessToken)
print(imgUrl)
send_message(imgUrl,sys.argv[1],sys.argv[2],imgUrl,sys.argv[4])
将脚本放入到:/usr/lib/zabbix/alertscripts/wxcom.py
设置报警媒介
xml模板文件下载:点击下载