共计 7266 个字符,预计需要花费 19 分钟才能阅读完成。
思路
1、通过zabbix传递给脚本的message参数,筛选出报警信息的itemid;
2、通过获取的itemid,在数据库中查找对应的grpahid;
3、拉取对应graphid的图片并保存;
4、使用微信API“上传临时素材”接口,将告警时保存的性能监控图上传,以获取“media_id”
5、使用获取到的“media_id为参数”,调用发送消息的API地址
代码实现
get_img
def get_itemid(self):
# 获取itemid
pattern = re.compile('ITEM.*?:(\d+)', re.S)
itemid = re.findall(pattern, sys.argv[3])
itemid = str(itemid).lstrip('[\'').rstrip('\']')
print(itemid)
return itemid
def get_graphid(self):
itemid = self.get_itemid()
conn = pymysql.connect(host=self.host, user=self.username, password=self.password, port=3306, db='zabbix')
cur = conn.cursor()
cur.execute("SELECT graphid FROM `graphs_items` WHERE `itemid`=%s;" % itemid)
result = cur.fetchone()
cur.close()
conn.close()
graphid = re.findall(r'\d+', str(result))
graphid = str(graphid).lstrip('[\'').rstrip('\']')
print(graphid)
return graphid
def get_img(self):
graphid = self.get_graphid()
# 拉取图片
os.system(
'curl -s -L -c /usr/lib/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -d "reauest=&name=%s&password=%s&autologin=1&enter=Sign+in" %s' % (
self.zabbix_user, self.zabbix_pwd, self.url))
os.system(
'curl -s -c /usr/lib/zabbix/alertscripts/cookie.txt -b /usr/lib/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -F "graphid=%s" -F "period=%s" -F "width=900" %s > /usr/lib/zabbix/img/zabbix_%s.png' % (
graphid, self.time, self.chart2_url, str(slerttime)))
img_name = '/usr/lib/zabbix/img/' + 'zabbix_' + str(self.alerttime) + '.png'
print(img_name)
return img_name
gettoken
def gettoken(corpid, corpsecret):
gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
print(gettoken_url)
try:
token_file = urllib.request.urlopen(gettoken_url)
except urllib.request.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
sys.exit()
token_data = token_file.read().decode('utf-8')
token_json = json.loads(token_data)
token_json.keys()
token = token_json['access_token']
return token
senddata
def senddata(self, access_token, user, subject, content):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
send_values = {
"touser": "wangxiao",
"msgtype": "textcard",
"agentid": "1000002",
"textcard": {
"title": "监控告警",
"description": subject + '\n' + content,
"url": "URL",
"btntxt": "更多"
},
"safe": "0"
}
send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
# print(send_data)
send_request = urllib.request.Request(send_url, send_data)
# print(send_request)
response = json.loads(urllib.request.urlopen(send_request).read())
print(str(response))
sendimg
def sendimg(access_token, user, subject, content):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
tm = datetime.datetime.now()
time = tm.strftime("%Y-%m-%d-%H%M")
savedir = '/data/img'
imgname = str(savedir) + '/' + 'zabbix_' + str(time) + '.jpg'
url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' + access_token + '&type=image'
files = {'file': open(imgname, 'rb')}
response = requests.post(url, files=files)
pattern = re.compile('media_id":"(.*?)",', re.S)
mediaid = re.findall(pattern, response.text)[-1]
send_values = {
"touser": "wangxiao",
"msgtype": "image",
"agentid": "1000002",
"image": {
"media_id": "%s" % mediaid
}
}
send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
print(send_data)
send_request = urllib.request.Request(send_url,send_data)
print(send_request)
response = json.loads(urllib.request.urlopen(send_request).read())
print(str(response))
全部代码
# -*- coding:utf-8 -*-
# !/usr/local/python3/bin/python3
import json
import urllib.request
import simplejson
import re, sys, os, requests, datetime, time
import pymysql
class zabbix_img(object):
def __init__(self, url, host, username, password, time):
# 指定zabbix获取图片的地址
self.chart2_url = 'http://172.20.2.11/zabbix/chart2.php'
# zabbix登录账户
self.zabbix_user = 'Admin'
# zabbix登录密码
self.zabbix_pwd = 'zabbix'
self.url = url
self.host = host
self.username = username
self.password = password
self.time = time
self.alerttime = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
def get_itemid(self):
# 获取itemid
pattern = re.compile('ITEM.*?(\d+)', re.S)
itemid = re.findall(pattern, sys.argv[3])
itemid = str(itemid).lstrip('[\'').rstrip('\']')
print(itemid)
return itemid
def get_graphid(self):
itemid = self.get_itemid()
conn = pymysql.connect(host=self.host, user=self.username, password=self.password, port=3306, db='zabbix')
cur = conn.cursor()
cur.execute("SELECT graphid FROM `graphs_items` WHERE `itemid`=%s;" % itemid)
result = cur.fetchone()
cur.close()
conn.close()
graphid = re.findall(r'\d+', str(result))
graphid = str(graphid).lstrip('[\'').rstrip('\']')
print(graphid)
return graphid
def get_img(self):
graphid = self.get_graphid()
# 拉取图片
os.system(
'curl -s -L -c /usr/lib/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -d "reauest=&name=%s&password=%s&autologin=1&enter=Sign+in" %s' % (
self.zabbix_user, self.zabbix_pwd, self.url))
os.system(
'curl -s -c /usr/lib/zabbix/alertscripts/cookie.txt -b /usr/lib/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -F "graphid=%s" -F "period=%s" -F "width=900" %s > /usr/lib/zabbix/img/zabbix_%s.png' % (
graphid, self.time, self.chart2_url, str(slerttime)))
img_name = '/usr/lib/zabbix/img/' + 'zabbix_' + str(self.alerttime) + '.png'
print(img_name)
return img_name
def gettoken(self, corpid, corpsecret):
gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
print(gettoken_url)
try:
token_file = urllib.request.urlopen(gettoken_url)
except urllib.request.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
sys.exit()
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 senddata(self, access_token, user, subject, content):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
send_values = {
"touser": "wangxiao",
"msgtype": "textcard",
"agentid": "1000002",
"textcard": {
"title": "监控告警",
"description": subject + '\n' + content,
"url": "URL",
"btntxt": "更多"
},
"safe": "0"
}
send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
# print(send_data)
send_request = urllib.request.Request(send_url, send_data)
# print(send_request)
response = json.loads(urllib.request.urlopen(send_request).read())
print(str(response))
def sendimg(self, access_token, user, subject, content):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
imgname = '/usr/lib/zabbix/img/' + 'zabbix_' + str(self.alerttime) + '.png'
url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' + access_token + '&type=image'
files = {'file': open(imgname, 'rb')}
response = requests.post(url, files=files)
pattern = re.compile('media_id":"(.*?)",', re.S)
mediaid = re.findall(pattern, response.text)[-1]
send_values = {
"touser": "wangxiao",
"msgtype": "image",
"agentid": "1000002",
"image": {
"media_id": "%s" % mediaid
}
}
send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
print(send_data)
send_request = urllib.request.Request(send_url, send_data)
print(send_request)
response = json.loads(urllib.request.urlopen(send_request).read())
print(str(response))
if __name__ == '__main__':
url = 'http://172.20.2.11/zabbix/index.php'
host = '172.20.2.11'
username = 'zabbix'
password = 'zabbix'
time = '600'
zabbixOper = zabbix_img(url, host, username, password, time)
zabbixOper.get_img()
user = sys.argv[1]
subject = sys.argv[2]
content = sys.argv[3]
corpid = 'wxf7141'
corpsecret = 'U0DaihOsLvSc'
accesstoken = zabbixOper.gettoken(corpid, corpsecret)
zabbixOper.senddata(accesstoken, user, subject, content)
zabbixOper.sendimg(accesstoken, user, subject, content)
注意事项:
[v_error]
1、务必将脚本放至zabbix执行脚本的目录
2、注意相关文件及目录的权限(cookie文件cookie.txt,脚本文件wechat.py,图片存储目录img)
[/v_error]
运行结果
禁ping模拟告警
接受告警
正文完