Python脚本通过邮件发送zabbix报警图片
程序员文章站
2024-03-18 13:40:04
...
Python脚本通过邮件发送zabbix报警图片流程如下:
通过zabbix传递给脚本的message参数,筛选出报警信息的itemid;
通过获取的itemid,在数据库中查找对应的grpahid;
拉取对应graphid的图片并保存;
将报警信息和图片组装成html;
发送邮件。
Python脚本如下:
#!/usr/bin/python
#coding=utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.p_w_picpath import MIMEImage
import MySQLdb,smtplib,sys,os,time,re
user=''
#zabbix用户名
password=''
#zabbix密码
url=''
#zabbix首页
period='3600'
chart2_url=''
#zabbix获取图片url http://192.168.0.1/chart2.php
mysql_host=''
mysql_user=''
mysql_pass=''
mysql_db=''
#zabbix数据库相关信息
graph_path='/usr/local/zabbix/alertscripts/'
#图片保存路径
def get_itemid():
#获取itemid
a=re.findall(r"ITEM ID: \d+",sys.argv[3])
i=str(a)
itemid=re.findall(r"\d+",i)
return str(itemid).lstrip('[\'').rstrip('\']')
def get_graphid(itemid):
#获取graphid
conn =MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db,connect_timeout=20)
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))
return str(graphid).lstrip('[\'').rstrip('\']')
def get_graph():
#拉取图片
time_tag=time.strftime("%Y%m%d%H%M%S", time.localtime())
os.system('curl -L -c /usr/local/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -d "reauest=&name=%s&password=%s&autologin=1&enter=Sign+in" %s' %(user,password,url))
os.system('curl -c /usr/local/zabbix/alertscripts/cookie.txt -b /usr/local/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -F "graphid=%s" -F "period=%s" -F "width=900" %s > /usr/local/zabbix/alertscripts/zabbix_%s_%s.png' %(graphid,period,chart2_url,graphid,time_tag))
graph_name= '/usr/local/zabbix/alertscripts/' + 'zabbix_' + graphid + '_' + time_tag +'.png'
return graph_name
def text_transfe_html(text):
#将message转换为html
d=text.splitlines()
html_text=''
for i in d:
i='' + i + '</br>'
html_text+=i + '\n'
return html_text
def send_mail(to_email,subject):
#发送邮件
graph_name=get_graph()
html_text=text_transfe_html(sys.argv[3])
smtp_host = 'smtp.exmail.qq.com'
from_email = ''
#邮箱账户
passwd = ''
#邮箱密码
msg=MIMEMultipart('related')
fp=open(graph_name,'rb')
p_w_picpath=MIMEImage(fp.read())
fp.close()
p_w_picpath.add_header('Content-ID','<p_w_picpath1>')
msg.attach(p_w_picpath)
html="""
<html>
<body>
"""
html+=html_text
html+='<img src="cid:p_w_picpath1"></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,to_email,msg.as_string())
smtp_server.quit()
if __name__ == '__main__':
to=sys.argv[1]
subject=sys.argv[2]
itemid=get_itemid()
graphid=get_graphid(itemid)
send_mail(to,subject)
脚本实现效果如下:
转载于:https://blog.51cto.com/147546/1829135
上一篇: Apache Lucene介绍与使用