Zabbix发送邮件告警(含告警图片)

需求背景

使用邮件发送zabbix告警,只能单纯的收到告警内容没有发生告警时的监控图片。使用python根据告警产生的itemid从数据库中获取到graphid然后下载图片,最后和邮件内容一同发出。

安装邮件发送工具

  • mailx

    1
    2
    3
    4
    5
    6
    7
    yum -y install mailx
    # 填写发送邮件的账户信息,需要先开通邮箱账户的POP3/SMTP服务
    vim /etc/mail.rc
    set bsdcompat
    set from=cloud-ome@****.com smtp=smtp.xxx.com
    set smtp-auth-user=**** smtp-auth-password=****
    set smtp-auth=login
  • postfix

    1
    2
    3
    4
    yum install -y postfix
    输入“alternatives --display mta”查看当前MTA
    如显示当前MTA为sendmail,则输入“/usr/sbin/alternatives --set mta /usr/sbin/sendmail.postfix”修改为postfix
    编辑vim /etc/postfix/main.cf

mark

zabbix配置

相关具体配置不再做过多说明,可自行网上查询
mark

python脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/python
#coding=utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import MySQLdb,smtplib,sys,os,time,re
user='****'
#zabbix用户名
password='****'
#zabbix密码
url='http://172.81.x.x/zabbix/'
#zabbix首页
period='900'
chart2_url='http://172.81.x.x/zabbix/chart2.php'
#zabbix获取图片url http://192.x.x.x/chart2.php
mysql_host='localhost'
mysql_user='zabbix'
mysql_pass='****'
mysql_db='zabbix'
#zabbix数据库相关信息
graph_path='/data/zabbix/img/'
#图片保存路径

def get_itemid():
#获取itemid
pattern = re.compile('ITEM.*?:(\d+)',re.S)
a = re.findall(pattern,sys.argv[3])
#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=10)
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/lib/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/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 > /data/zabbix/img/zabbix_%s_%s.png' %(graphid,period,chart2_url,graphid,time_tag))
graph_name= '/data/zabbix/img/' + '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.xxxx'
from_email = 'liykxxxx'
#邮箱账户
passwd = 'xxxx'
#邮箱密码
msg=MIMEMultipart('related')
fp=open(graph_name,'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','utf-8')
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]
with open('/tmp/zabbix.log','w') as f:
f.write(to)
subject=sys.argv[2]
itemid=get_itemid()
graphid=get_graphid(itemid)
for i in to.strip().split(','):
send_mail(i,subject)

mark

-------------本文结束感谢您的阅读-------------
原创技术分享,感谢您的支持。