Pythonスクリプトに基づいてメールアラーム機能を実現します。
smatplibなどの第三者ライブラリを使ってメールを送り、メールアラーム機能を完成させました。
実例は以下の通りです
エリック[email protected]-「[ERROR/$HOST]File Stocing Alarm」
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。
実例は以下の通りです
#!/usr/bin/python
import glob
import operator
from optparse import OptionParser
import smtplib
import email.MIMEText as MIMEText
import email.Utils.formadate as formatdate
msg = ""
#
def main():
global options
global msg
parser = OptionParser(add_help_option=False)
parser.add_option("-m", "--mail", dest="mail", type="str", help="email address to send report result (comma separated)")
parser.add_option("-t", "--title", dest="title", type="str", help="email title (default:Error File Count)")
parser.add_option("-a", "--admin", dest="admin", type="str", help="set sender address. works with -m option")
(options, args) = parser.parse_args()
# , 25
datanum = cntFiles("/data/","csv")
if (operator.gt(datanum,25)):
msg += " Please be alert :
the number of files under /data/ path is greater than 25 :"
msg += "
=========================================="
msg += "
The number of files is : " + str(datanum)
sendmsg(options,msg)
print("==== end ====")
#
def sendmsg(options,msg):
if options.mail:
toAddr = options.mail
if options.admin:
fromAddr = options.admin
else:
fromAddr = '[email protected]'# SMTP
if options.title:
subject = options.title
else:
subject = 'File Stacking Alarm'
msg += "
==========================================
"
print( msg)
msg = createMsg(fromAddr, toAddr, subject, msg)
print( msg)
send(fromAddr, toAddr, msg)
else:
print( msg)
#glob ,
def cntFiles(in_directory, ext):
stage = len(glob.glob1(in_directory,"*." + ext))
return stage
#
def createMsg(fromAddr, toAddr, subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['To'] = toAddr
msg['From'] = fromAddr
msg['Date'] = formatdate()
return msg
#
def send(fromAddr, toAddr, msg):
try:
# SMTP
s = smtplib.SMTP('192.168.12.120')
s.sendmail(fromAddr, toAddr.split(','), msg.as_string())
s.close()
print("SUCCESS: sending email")
except smtplib.SMTPException:
print("ERROR: sending email")
if __name__ == '__main__':
main()
linuxで計画的なタスクを行い、命令を計画的なタスクに追加します。エリック[email protected]-「[ERROR/$HOST]File Stocing Alarm」
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。