Zabbix 告警附带原生图片
环境: centos8
python3.6.8
/usr/lib/zabbix/alertscripts/
具体思路
该脚本具体思路是模拟登陆通过获取到itemid去进去对应的链接,然后再去获取对应图片的URL,通过传参去获取图片,将获取到的图片保存到对应的地址上,然后再去读取图片的位置,将图片用HTML的语句的方式去发送图片。
怎么调用脚本去发送邮件到对应的账号里面-zabbix的操作
1、
2、
Problem: {EVENT.NAME}
Problem started at {EVENT.TIME} on {EVENT.DATE}
Problem name: {EVENT.NAME}
Host: {HOST.NAME}
Severity: {EVENT.SEVERITY}
Operational data: {EVENT.OPDATA}
Original problem ID: {EVENT.ID}
{TRIGGER.URL}
3、
4、
5、
6、
Zabbix告警:服务器:{HOSTNAME}发生: {TRIGGER.NAME}故障!
监控ID:{ITEM.ID}
告警主机:{HOST.NAME}
告警主机:{HOST.IP}
告警时间:{EVENT.DATE} {EVENT.TIME}
告警等级:{TRIGGER.SEVERITY}
告警信息: {TRIGGER.NAME}
告警项目:{TRIGGER.KEY}
问题详情:{ITEM.NAME}:{ITEM.VALUE}
当前状态:{TRIGGER.STATUS}:{ITEM.VALUE}
事件ID:{EVENT.ID}
7、
Zabbix告警:服务器:{HOST.NAME}发生: {TRIGGER.NAME}已恢复!
监控ID:{ITEM.ID}
告警主机:{HOST.NAME}
告警主机:{HOST.IP}
告警时间:{EVENT.DATE} {EVENT.TIME}
告警等级:{TRIGGER.SEVERITY}
告警信息: {TRIGGER.NAME}
告警项目:{TRIGGER.KEY}
怎么调用脚本去发送邮件到对应的账号里面-服务器的操作
在服务器上面我们也要给zabbix设置一些权限否则就无法成功发送告警邮件
首先进入zabbix_server.conf
修改如下内容:
还有一点就是要给脚本和文件加权限,否则就会因为权限报错,无法运行
chmod 777 xxxx
成功案例:
#!/usr/bin/env python3
import requests
import os, stat, datetime
import urllib.request
import datetime
import time as Time
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import parseaddr, formataddr
from smtplib import SMTP
import sys
# 邮件标题
email_title = sys.argv[2]
# 邮件内容
#email_msg = sys.argv[3]
sender = 'xxx'# 发送人邮箱地址
# 收件人邮箱地址
to_address = ['xxxx']
cc_address = ['xxx']
host = 'xxxxxxx' #zabbix的IP地址
username = 'xxx' # 发送人账号
password = 'xxxx0'# 发送人密码
smtp_server = 'xxxx' # STMP服务器地址
n_day = 1# 截取多少天前的图表
headers = {
"Host": host,
"Origin": "https://" + host,
"Referer": "https://{}/zabbix/index.php".format(host),
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36",
}
session = requests.session()
session.headers = headers
def get_itemid():
#获取报警的itemid
itemid=re.search(r'监控ID:(\d+)',sys.argv[3]).group(1)
return itemid
def monidenglu(id):
url = 'https://{}/zabbix/index.php'.format(host)
data = {
"name": "Admin",
"password": "zabbix",
"autologin": "1",
"enter": "登录",
}
html = session.post(url=url,headers=headers,data=data,verify=False)
if html.status_code == 200:
get_html(session,id)
else:
print(html.status_code)
def get_html(sess,itemid):
# 定义获取图片的参数
graph_params = {
"from":"now-1h",
"to":"now",
"itemids[0]": itemid,
"type": "0",
"profileIdx": "web.item.graph.filter",
"profileIdx2": itemid,
"width": "1820",
"height":"600",
}
graph_url = 'https://{}/zabbix/chart.php?'.format(host)
#模拟登陆,发送get请求获取图片数据
graph_req = sess.get(url=graph_url, params=graph_params,verify=False)
#获取当前时间,用于给图片命名
time_tag = Time.strftime("%Y%m%d%H%M%S", Time.localtime())
year = time_tag[0:4]
month = time_tag[4:6]
day = time_tag[6:8]
graph_name = '{}'.format(itemid)+'.png'
# #创建保存图片的文件,如果不存在便创建文件夹
graph_path = '/usr/lib/zabbix/alertscripts/img/{}/{}/{}'.format(year,month,day)
if not os.path.exists(graph_path):
os.makedirs(graph_path)
# 使用绝对路径保存图片
graph_name = os.path.join(graph_path, graph_name)
# 将获取到的图片数据写入到文件中去
with open(graph_name, 'wb') as f:
f.write(graph_req.content)
img_path = graph_name
send_mail_pis(img_path)
# 获取多日前0点与今日0点的时间戳
def getYesterday(day):
today = datetime.date.today()
oneday = datetime.timedelta(days=day)
yesterday = today - oneday
today_ = str(today) + " 0:00:00"
yesterday_ = str(yesterday) + " 0:00:00"
todayArray = Time.strptime(today_, "%Y-%m-%d %H:%M:%S")
yesterdayArray = Time.strptime(yesterday_, "%Y-%m-%d %H:%M:%S")
todayStamp = int(Time.mktime(todayArray)) * 1000
yesterdayStamp = int(Time.mktime(yesterdayArray)) * 1000
return str(yesterdayStamp), str(todayStamp), str(yesterday)
def text_to_html(text):
#将邮件内容text字段转换成HTML格式
d=text.splitlines()
#将邮件内容以每行作为一个列表元素存储在列表中
html_text=''
for i in d:
i='' + i + '<br>'
html_text+=i + '\n'
#为列表的每个元素后加上html的换行标签
return html_text
# 发送多张图片邮件
def send_mail_pis(graph_path):
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = email_title
msgRoot['From'] = sender
msgRoot['To'] = ",".join(to_address) # 发给多人
msgRoot['Cc'] = ",".join(cc_address) # 发给多人
mail_html = open("/usr/lib/zabbix/alertscripts/mail.html", "r", encoding="utf-8").read()
yesterdayIs = str(getYesterday(1)[2]).split("-")
mail_html = mail_html.replace("{#time1}", Time.strftime("%H:%M %d/%m/%Y", Time.localtime()))
mail_html = mail_html.replace("{#title}", email_title)
mail_html = mail_html.replace("{#title1}", email_title.replace("日报", ""))
text=text_to_html(sys.argv[3])
mail_html = mail_html.replace("{#msg}", text)
#对图片进行定位
insert_img_str = """
<br><img src="cid:image%s" alt="image%s"><br><!-- imgend -->
""" % (graph_path,graph_path)
mail_html = re.sub("<!-- imgend -->", insert_img_str, mail_html)
content = MIMEText(mail_html, 'html', 'utf-8')
msgRoot.attach(content)
# 获取图片
fp = open('{}'.format(graph_path), 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', 'image' + str(graph_path)) # 该id和html中的img src对应
msgRoot.attach(msgImage)
# signature_img_file = 'img/signature.png'
# fp = open(signature_img_file, 'rb')
# msgImage = MIMEImage(fp.read())
# fp.close()
# msgImage.add_header('Content-ID', 'image_sign') # 该id和html中的img src对应
# msgRoot.attach(msgImage)
smtp = SMTP(smtp_server, '587')
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(sender, to_address + cc_address, msgRoot.as_string())
smtp.quit()
file_name = 'log'
fp = open(file_name, "a", encoding="utf-8")
fp.write(Time.strftime("%Y-%m-%d %H:%M:%S", Time.localtime()) + " 邮件已发送\n")
fp.close()
if __name__ == '__main__':
#这里输入要监控的图像监控项的id
itemid = get_itemid()
monidenglu(itemid)
print('发送成功')
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<meta name=Generator content="Microsoft Word 15 (filtered medium)">
<!--[if !mso]><style>v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style><![endif]-->
<style>
<!--
/* Font Definitions */
@font-face {
font-family: 宋体;
panose-1: 2 1 6 0 3 1 1 1 1 1;
}
@font-face {
font-family: "Cambria Math";
panose-1: 2 4 5 3 5 4 6 3 2 4;
}
@font-face {
font-family: 等线;
panose-1: 2 1 6 0 3 1 1 1 1 1;
}
@font-face {
font-family: Calibri;
panose-1: 2 15 5 2 2 2 4 3 2 4;
}
@font-face {
font-family: "\@宋体";
panose-1: 2 1 6 0 3 1 1 1 1 1;
}
@font-face {
font-family: "\@等线";
panose-1: 2 1 6 0 3 1 1 1 1 1;
}
@font-face {
font-family: 微软雅黑;
panose-1: 2 11 5 3 2 2 4 2 2 4;
}
@font-face {
font-family: "\@微软雅黑";
}
/* Style Definitions */
p.MsoNormal,
li.MsoNormal,
div.MsoNormal {
margin: 0cm;
margin-bottom: .0001pt;
text-align: justify;
text-justify: inter-ideograph;
font-size: 10.5pt;
font-family: 等线;
}
a:link,
span.MsoHyperlink {
mso-style-priority: 99;
color: #0563C1;
text-decoration: underline;
}
a:visited,
span.MsoHyperlinkFollowed {
mso-style-priority: 99;
color: #954F72;
text-decoration: underline;
}
p.msonormal0,
li.msonormal0,
div.msonormal0 {
mso-style-name: msonormal;
mso-margin-top-alt: auto;
margin-right: 0cm;
mso-margin-bottom-alt: auto;
margin-left: 0cm;
font-size: 12.0pt;
font-family: 宋体;
}
span.EmailStyle18 {
mso-style-type: personal;
font-family: "Calibri", sans-serif;
color: black;
}
span.EmailStyle19 {
mso-style-type: personal;
font-family: 等线;
color: windowtext;
}
span.EmailStyle20 {
mso-style-type: personal;
font-family: 等线;
color: windowtext;
}
span.EmailStyle21 {
mso-style-type: personal;
font-family: 等线;
color: #1F497D;
}
span.EmailStyle22 {
mso-style-type: personal;
font-family: 等线;
color: #1F497D;
}
span.EmailStyle23 {
mso-style-type: personal;
font-family: 等线;
color: #1F497D;
}
span.EmailStyle24 {
mso-style-type: personal;
font-family: 等线;
color: #1F497D;
}
span.EmailStyle25 {
mso-style-type: personal;
font-family: 等线;
color: #1F497D;
}
span.EmailStyle26 {
mso-style-type: personal-reply;
font-family: 等线;
color: #1F497D;
}
.MsoChpDefault {
mso-style-type: export-only;
font-size: 10.0pt;
}
@page WordSection1 {
size: 612.0pt 792.0pt;
margin: 72.0pt 90.0pt 72.0pt 90.0pt;
}
div.WordSection1 {
page: WordSection1;
}
-->
</style>
<!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026" />
</xml><![endif]-->
<!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1" />
</o:shapelayout></xml><![endif]-->
</head>
<body lang=ZH-CN link="#0563C1" vlink="#954F72" style='text-justify-trim:punctuation'>
<div class=WordSection1>
<p class=MsoNormal align=left style='text-align:left'><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif'></span><span
style='font-size:12.0pt;font-family:"Calibri",sans-serif;color:#1F497D'> <span lang=EN-US>
<o:p></o:p>
</span></span></p>
<p class=MsoNormal align=left style='text-align:left'><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'></span><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif'>{#msg}</span><span
style='font-size:12.0pt;font-family:"Calibri",sans-serif'> <span lang=EN-US>
<o:p></o:p>
</span></span></p>
<p class=MsoNormal align=left style='text-align:left'><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif'></span><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'> </span><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif'></span><span
style='font-size:12.0pt;font-family:"Calibri",sans-serif'> <span lang=EN-US>
<o:p></o:p>
</span></span></p>
<p class=MsoNormal align=left style='text-align:left'><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif'></span><span
style='font-size:12.0pt;font-family:"Calibri",sans-serif'> </span><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'><a
href="mailto:gz_dsoc@macroview.com"></a></span><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'>
<o:p></o:p>
</span></p>
<p class=MsoNormal align=left style='text-align:left'><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif'></span><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'><o:p></o:p></span></p>
<p class=MsoNormal align=left style='text-align:left'><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'>
<o:p> </o:p>
</span></p>
<p class=MsoNormal><b><u><span lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'>Statistics
Performance Summary</span></u></b><b><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'> </span></b><b><u><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'>
<o:p></o:p>
</span></u></b></p>
<p class=MsoNormal><b><span lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'>Report Time:
</span></b><span lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'>{#time1}</span><span
lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'> </span><span lang=EN-US
style='font-size:12.0pt;font-family:"Calibri",sans-serif'>
<o:p></o:p>
</span></p>
<p class=MsoNormal><b><span lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'></span></b><span lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'> </span><span
lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'><o:p>
</o:p></span></p>
<p class=MsoNormal><span lang=EN-US style='font-size:12.0pt;font-family:"Calibri",sans-serif'>
<o:p> </o:p>
</span></p>
<p class=MsoNormal align=center style='text-align:center'><b><span
style='font-size:12.0pt;font-family:"微软雅黑",sans-serif;color:black'>{#title1}</span></b><b><span
style='font-family:"微软雅黑",sans-serif'> <span lang=EN-US style='color:black'>
<o:p></o:p>
</span></span></b></p>
<!-- imgstart -->
<!-- imgend -->
</div>
</body>
</html>