您好,登錄后才能下訂單哦!
這篇文章主要講解了基于Python腳本實現郵件報警功能的方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
使用了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", 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 : \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 = 'zhangsan@neiyou.cn'#這里是公司的公用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, 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上做計劃任務,把指令添加進計劃任務中:
Errymsfileemail.py -m zhangsan@gongsi.cn -t "[ERROR/$HOST] File Stacking Alarm"
看完上述內容,是不是對基于Python腳本實現郵件報警功能的方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。