基於Python指令碼實現郵件報警功能
阿新 • • 發佈:2020-05-20
使用了smtplib等第三方庫,進行傳送郵件,完成郵件報警功能
如下是例項 :
#!/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",help="email title (default:Error File Count)") parser.add_option("-a","--admin",dest="admin",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 : \n the number of files under /data/ path is greater than 25 :" msg += "\n ==========================================" msg += "\n 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 += "\n ========================================== \n" print( msg) msg = createMsg(fromAddr,toAddr,subject,msg) print( msg) send(fromAddr,msg) else: print( msg) #glob方法,統計資料夾下的檔案數 def cntFiles(in_directory,ext): stage = len(glob.glob1(in_directory,"*." + ext)) return stage #建立郵件頭 def createMsg(fromAddr,body): msg = MIMEText(body) msg['Subject'] = subject msg['To'] = toAddr msg['From'] = fromAddr msg['Date'] = formatdate() return msg #傳送郵件 def send(fromAddr,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上做計劃任務,把指令新增進計劃任務中:
Errymsfileemail.py -m [email protected] -t "[ERROR/$HOST] File Stacking Alarm"
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。