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 = ‘[email protected]‘ password = ‘xxxxxxxx‘ 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(): headerInfo = u"ZabbixServer报警信息" fromInfo = u"Zabbix监控" bodyInfo = ZabbixInfo() 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
时间: 2024-11-04 11:30:58