基于Python脚本实现邮件报警功能
使用了smtplib等第三方库,进行发送邮件,完成邮件报警功能
如下是实例:
#!/usr/bin/python importglob importoperator fromoptparseimportOptionParser importsmtplib importemail.MIMETextasMIMEText importemail.Utils.formadateasformatdate msg="" #主方法 defmain(): globaloptions globalmsg parser=OptionParser(add_help_option=False) parser.add_option("-m","--mail",dest="mail",type="str",help="emailaddresstosendreportresult(commaseparated)") parser.add_option("-t","--title",dest="title",type="str",help="emailtitle(default:ErrorFileCount)") parser.add_option("-a","--admin",dest="admin",type="str",help="setsenderaddress.workswith-moption") (options,args)=parser.parse_args() #这里监控文件夹下的文件数,超出25个文件即报警 datanum=cntFiles("/data/","csv") if(operator.gt(datanum,25)): msg+="Pleasebealert:\nthenumberoffilesunder/data/pathisgreaterthan25:" msg+="\n==========================================" msg+="\nThenumberoffilesis:"+str(datanum) sendmsg(options,msg) print("====end====") #添加发送邮件的信息 defsendmsg(options,msg): ifoptions.mail: toAddr=options.mail ifoptions.admin: fromAddr=options.admin else: fromAddr='zhangsan@neiyou.cn'#这里是公司的公用SMTP邮箱账号 ifoptions.title: subject=options.title else: subject='FileStackingAlarm' msg+="\n==========================================\n" print(msg) msg=createMsg(fromAddr,toAddr,subject,msg) print(msg) send(fromAddr,toAddr,msg) else: print(msg) #glob方法,统计文件夹下的文件数 defcntFiles(in_directory,ext): stage=len(glob.glob1(in_directory,"*."+ext)) returnstage #创建邮件头 defcreateMsg(fromAddr,toAddr,subject,body): msg=MIMEText(body) msg['Subject']=subject msg['To']=toAddr msg['From']=fromAddr msg['Date']=formatdate() returnmsg #发送邮件 defsend(fromAddr,toAddr,msg): try: #这里添加公司的SMTP邮箱地址 s=smtplib.SMTP('192.168.12.120') s.sendmail(fromAddr,toAddr.split(','),msg.as_string()) s.close() print("SUCCESS:sendingemail") exceptsmtplib.SMTPException: print("ERROR:sendingemail") if__name__=='__main__': main()
linux上做计划任务,把指令添加进计划任务中:
Errymsfileemail.py-mzhangsan@gongsi.cn-t"[ERROR/$HOST]FileStackingAlarm"
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。