共计 4922 个字符,预计需要花费 13 分钟才能阅读完成。
思路
- 通过zabbix传递给脚本的message参数,筛选出报警信息的itemid;
- 通过获取的itemid,在数据库中查找对应的grpahid;
- 拉取对应graphid的图片并保存;
- 将报警信息和图片组装成html;
- 发送邮件
脚本
获取itemid
从zabbix传来的第三个参数(message)中,通过re过滤出itemid
def get_itemid(self): | |
# 获取itemid | |
pattern = re.compile('ITEM.*?:(\d+)',re.S) | |
itemid = re.findall(pattern,sys.argv[3]) | |
itemid = str(itemid).lstrip('[\'').rstrip('\']') | |
return itemid |
获取graphid
将上一步得到的itemid传入该函数,并通过pymysql连接zabbix-server所在的数据库进行查询,得到graphid
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 |
获取性能监控图片url并保存至文件
def get_img(self): | |
time = self.time | |
graph_id = self.get_graphid() | |
img_url = 'http://' + str(self.host) +'/zabbix/' + 'chart2.php?graphid=%s&period=%s&isNow=1&profileIdx=web.graphs&profileIdx2=797&width=1000' %(graph_id,time) | |
print(img_url) | |
try: | |
response = requests.get(img_url,headers = self.headers) | |
if response.status_code == 200: | |
return response.content | |
else: | |
return None | |
except Exception as e: | |
print(e) | |
def save_img(self): | |
content = self.get_img() | |
tm = datetime.datetime.now() | |
time = tm.strftime("%Y-%m-%d-%H%M%S") | |
string = str(self.savedir) + '/' + 'zabbix_' + str(time) + '.jpg' | |
fp = open(string, 'wb') | |
fp.write(content) | |
fp.close() | |
return string |
发送邮件
def sendmail(self,toemail,subject): | |
imgname = self.save_img() | |
html_text = self.convert_to_html(sys.argv[3]) | |
smtp_host = 'smtp.qq.com' | |
from_email = 'zabbix@cloudcared.cn' | |
passwd = 'stlq' | |
msg = MIMEMultipart('related') | |
fp = open(imgname, 'rb') | |
image = MIMEImage(fp.read()) | |
fp.close() | |
image.add_header('Content-ID', '<image1>') | |
msg.attach(image) | |
html = """ | |
<html> | |
<body> | |
""" | |
html += html_text | |
html += '<img src="cid:image1"></br>' | |
html += """ | |
</body> | |
</html> | |
""" | |
html = MIMEText(html, 'html', 'gb2312') | |
msg.attach(html) | |
msg['Subject'] = subject | |
msg['From'] = from_email | |
smtp_server = smtplib.SMTP_SSL() | |
smtp_server.connect(smtp_host, '465') | |
smtp_server.login(from_email, passwd) | |
smtp_server.sendmail(from_email, toemail, msg.as_string()) | |
smtp_server.quit() | |
print(imgname) |
最终代码
# -*- coding:utf-8 -*- | |
#!/usr/local/python3/bin/python3 | |
import smtplib | |
from email.mime.text import MIMEText | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.image import MIMEImage | |
import pymysql | |
import re,sys,os,requests,datetime,time | |
class zabbix_img(object): | |
def __init__(self,url,host,username,password,time): | |
self.host = host | |
# 指定zabbix获取图片的地址 | |
self.chart2_url = 'http://172.20.2.11/zabbix/chart2.php' | |
# zabbix登录账户 | |
self.zabbix_user = 'Admin' | |
# zabbix登录密码 | |
self.zabbix_pwd = 'zabbix' | |
self.username = username | |
self.password = password | |
self.url = url | |
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('\']') | |
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 -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 -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(self.alerttime))) | |
img_name = '/usr/lib/zabbix/img/' + 'zabbix_' + str(self.alerttime) + '.png' | |
print(img_name) | |
return img_name | |
def convert_to_html(self,text): | |
d = text.splitlines() | |
html_text = '' | |
for i in d: | |
i = '' + i + '</br>' | |
html_text += i + '\n' | |
return html_text | |
def sendmail(self,toemail,subject): | |
imgname = self.get_img() | |
html_text = self.convert_to_html(sys.argv[3]) | |
smtp_host = 'smtp.qq.com' | |
from_email = 'zabbix@cloudcared.cn' | |
passwd = 'stlqpedmjshrcahb' | |
msg = MIMEMultipart('related') | |
fp = open(imgname, 'rb') | |
image = MIMEImage(fp.read()) | |
fp.close() | |
image.add_header('Content-ID', '<image1>') | |
msg.attach(image) | |
html = """ | |
<html> | |
<body> | |
""" | |
html += html_text | |
html += '<img src="cid:image1"></br>' | |
html += """ | |
</body> | |
</html> | |
""" | |
html = MIMEText(html, 'html', 'gb2312') | |
msg.attach(html) | |
msg['Subject'] = subject | |
msg['From'] = from_email | |
smtp_server = smtplib.SMTP_SSL() | |
smtp_server.connect(smtp_host, '465') | |
smtp_server.login(from_email, passwd) | |
smtp_server.sendmail(from_email, toemail, msg.as_string()) | |
smtp_server.quit() | |
print(imgname) | |
def main(): | |
url = 'http://172.20.2.11/zabbix/index.php' | |
host = '172.20.2.11' | |
username = 'zabbix' | |
password = 'zabbix' | |
time = '600' | |
to = sys.argv[1] | |
subject = sys.argv[2] | |
zabbixOper = zabbix_img(url,host,username,password,time) | |
zabbixOper.get_img() | |
zabbixOper.sendmail(to,subject) | |
if __name__ == '__main__': | |
main() |
测试
正文完