#!/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:
./sendmail -t 'eric@nginxs.com' -s 'hello eric' -p /tmp/nagios-mail '"""
sys.exit(3)
try:
options,args = getopt.getopt(sys.argv[1:],"ht:s:p:",["--help","--to=","--subject=","--path="])
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 ("-p","--path"):
MESSAGE = value #传入文件路径
MESSAGE = open(MESSAGE,'r') #只读模式打开文件
MESSAGE = MESSAGE.read() #读取文件内容
#smtp HOST
HOST = "smtp.126.com"
#smtp port
PORT = "25"
#FROM mail user
USER = 'eric'
#FROM mail password
PASSWD = '123456'
#FROM EMAIL
FROM = "yangzi2008@126.com"
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"
注意:
改动了 message 以读文件内容方式传入,放弃了以参数方法传入。
-m 擦数改为 -p参数 -p 后面 跟 文件的 绝对路径。
修改 nagios 的 commands.cfg