烹茶细论

zabbix邮件报警设置

之前用的是cacti监控,最近尝试搭建了zabbix,主机添加、图像展示、自动发现主机的功能都已经设置好。于是开始设置你邮件报警功能

一、使用postfix和mailx发送邮件
centos6.4已经默认安装postfix
yum install mailx
编辑配置文件/etc/mail.rc,文件末尾添加

1
2
3
set from=**@**.com smtp=mail.**.com
set smtp-auth-user=**@**.com smtp-auth-password=123456****
set smtp-auth=login

测试

1
echo "内容" | mail -s "Zabbix邮件" '**@**.com'

能够正常收到邮件则表示设置OK

sendmail.sh脚本

1
2
#!/bin/sh
echo "$3" | mail -s "Zabbix邮件 $2" $1

编辑zabbix_server.conf,指定发送邮件脚本

1
AlertScriptsPath=/data/zabbix/scripts/

zabbix_action

zabbix_action2

zabbix_action3

email

二、使用python脚本发送邮件
zabbix的设置只是指定脚本不一样而已,其他一样即可
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
#!/usr/bin/python
# coding: utf-8
import smtplib,email,datetime,uuid,os,sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
reload(sys).setdefaultencoding('utf-8')
def send_mail(sub,content,mail_to):
#设置服务器,用户名、口令以及邮箱的后缀
#global mail_to
mail_host="mail.**.com"
mail_name=u"报警平台"
mail_user="sta"
mail_pass="****"
mail_postfix="**.com"
msg = MIMEMultipart()
body = MIMEText(content,"html",'utf-8')
msg['Subject'] = sub
msg['From'] = formataddr((mail_name,mail_user + "@" + mail_postfix))
#msg['To'] = ";".join(mail_to)
msg['To'] = mail_to
msg.attach(body)
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(mail_user + "@" + mail_postfix, mail_to,msg.as_string())
s.sendmail(mail_user + "@" + mail_postfix, ["**@**.com"],msg.as_string())
s.close()
return True
except Exception, e:
print str(e)
if __name__ == '__main__':
#获取由zabbix传入的收件人、邮件主题和邮件正文
email_to = sys.argv[1]
subject = sys.argv[2]
content = sys.argv[3]
#发送邮件
send_mail(subject, content, email_to)