Zabbix调用外部脚本发送邮件的时候,会在命令行传入两个参数,第一个参数就是要发送给哪个邮箱地址,第二个参数就是邮件信息,为了保证可以传入多个参数,所以假设有多个参数传入
#!/usr/bin/env python
#encoding:utf8
#
# Zabbix Server 发送邮件脚本
#
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
import sys
from_addr = 'shixunwuxian@163.com'
password = '123qwe'
smtp_server = 'smtp.163.com'
# 报警邮件收件人
to_addr = sys.argv[1]
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( \
Header(name, 'utf-8').encode(), \
addr.encode('utf-8') if isinstance(addr, unicode) else addr))
def ZabbixInfo():
res = ""
itemList = sys.argv
for index in range(2, len(itemList)):
res = res + itemList[index]
return res
def sendMsg():
bodyInfo = ZabbixInfo()
headerInfo = str(bodyInfo.split('<*>')[1])
fromInfo = u"Zabbix监控"
msg = MIMEText(bodyInfo , 'plain', 'utf-8')
msg['From'] = _format_addr(fromInfo + "<%s>" % from_addr)
msg['To'] = _format_addr(fromInfo + "<%s>" % to_addr)
msg['Subject'] = Header(headerInfo, 'utf-8').encode()
return msg.as_string()
def main():
server = smtplib.SMTP(smtp_server, 25)
#server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], sendMsg())
server.quit()
if __name__ == "__main__":
main()
脚本中的163邮箱的密码不是登陆密码,是pop3方式的专用密码
下面是日志图片,使用的zabbix版本比较老,保证运行稳定,少BUG