之前公司nagios发送邮件的脚本是用expect来写的,但是一直有一个弊端就是nagios邮件正文不能换行,只能在一行显示,每次报警看起来都很费劲。一直想换了它,这次用python的脚本就解决的这个换行的问题。 废话少说,上脚本:
#!/usr/bin/python import smtplib import string import sys import getopt def usage(): print """sendmail is a send mail Plugins Usage: sendmail [-h|--help][-t|--to][-s|--subject][-m|--message] Options: --help|-h) print sendmail help. --to|-t) Sets sendmail to email. --subject|-s) Sets the mail subject. --message|-m) Sets the mail body Example: only one to email user ./sendmail -t 'eric@nginxs.com' -s 'hello eric' -m 'hello eric,this is sendmail test! many to email user ./sendmail -t 'eric@nginxs.com,zhangsan@nginxs.com' -s 'hello eric' -m 'hello eric,this is sendmail test!""" sys.exit(3) try: options,args = getopt.getopt(sys.argv[1:],"ht:s:m:",["help","to=","subject=","message="]) except getopt.GetoptError: usage() for name,value in options: if name in ("-h","--help"): usage() if name in ("-t","--to"): # accept message user TO = value TOTO = TO.split(",") if name in ("-s","--title"): SUBJECT = value if name in ("-m","--message"): MESSAGE = value MESSAGE = MESSAGE.split('\\n') MESSAGE = '\n'.join(MESSAGE) #smtp HOST HOST = "smtp.126.com" #改为你的邮局SMTP 主机地址 #smtp port PORT = "25" #改为你的邮局的SMTP 端口 #FROM mail user USER = 'eric' # 改为你的邮箱用户名 #FROM mail password PASSWD = '123456' # 改为你的邮箱密码 #FROM EMAIL FROM = "test@163.com" # 改为你的邮箱 email try: BODY = string.join(( "From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT, "", MESSAGE),"\r\n") smtp = smtplib.SMTP() smtp.connect(HOST,PORT) smtp.login(USER,PASSWD) smtp.sendmail(FROM,TO,BODY) smtp.quit() except: print "UNKNOWN ERROR" print "please look help" - print "./sendmail -h"
使用方法: 只给一个用户发: nagios $> ./sendmail -t 'test@163.com' -s 'hello' -m 'hello,this is sendmail test! 给多个用户发: 应用到nagios上,用来报警: [root@master ~]# vim /etc/nagios/objects/commands.cfg define command{ command_name notify-host-by-email command_line $USER1$/sendmail -t $CONTACTEMAIL$ -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" -m "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" }
define command{ command_name notify-service-by-email command_line $USER1$/sendmail -t $CONTACTEMAIL$ -s "** $NOTIFICATIONTYPE$ Service Alert: $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$ **" -m "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\n\nService: $SERVICEDESC$\nHost: $HOSTALIAS$\nAddress: $HOSTADDRESS$\nState: $SERVICESTATE$\n\nDate/Time: $LONGDATETIME$\n\nAdditional Info:\n\n$SERVICEOUTPUT$" } [root@master ~]# /etc/init.d/nagios reload 这样就可以了。 |