python指令碼用來nagios發送郵件
之前公司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
TO = 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!
給多個使用者發:
./sendmail -t ' test@163.com,test02@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
這樣就可以了。
本文出自 “夢想照進現實” 部落格,請務必保留此出處http://zhhmj.blog.51cto.com/1666742/990830