Python实现报警信息实时发送至邮箱功能(实例代码)
Python实现报警信息实时发送至邮箱功能,具体内容如下所示:
程序设计
实现代码
cpu.py
#-*-coding:utf-8-*- importpsutil importtime fromemailsenderimporttxtMail fromlogimportmyloggers importgc classmycpumonitor(): #up是cpu监控的阈值,默认是90% def__init__(self,up=None): self.up=90ifupisNoneelseup defcpu_monitor(self): cpu_percent=psutil.cpu_percent() now=time.strftime("%Y-%m-%d%H:%M:%S",time.localtime()) ifcpu_percent>self.up: filename='cpu.txt' withopen(filename,'w')asf:#如果filename不存在会自动创建,'w'表示写数据,写之前会清空文件中的原有数据! f.write(str(now)+"CPU使用率超过"+str(self.up)+"!!!!.\n") f.write(str(now)+"当前CPU使用率"+str(cpu_percent)+"!!!\n") mail=txtMail() try: mail.txt_send_mail(filename="test.config",alarm=filename) temp_msg="CPU超标,当前CPU使用率:"+str(cpu_percent) logger1=myloggers(temp_msg) logger1.maillogging() delmail gc.collect() except: print("文本文件格式不正确")
mem.py
#-*-coding:utf-8-*- importpsutil importtime fromemailsenderimporttxtMail fromlogimportmyloggers importgc classmymemmonitor(): #up是内存监控的阈值,默认是90% def__init__(self,up=None): self.up=90ifupisNoneelseup defmem_monitor(self): mem_percent=psutil.virtual_memory()[2] now=time.strftime("%Y-%m-%d%H:%M:%S",time.localtime()) ifmem_percent>self.up: filename='mem.txt' withopen(filename,'w')asf:#如果filename不存在会自动创建,'w'表示写数据,写之前会清空文件中的原有数据! f.write(str(now)+"内存使用率超过"+str(self.up)+"!!!!.\n") f.write(str(now)+"当前内存使用率"+str(mem_percent)+"!!!\n") mail=txtMail() try: mail.txt_send_mail(filename="test.config",alarm=filename) temp_msg="内存超标,当前内存使用率:"+str(mem_percent) logger1=myloggers(temp_msg) logger1.maillogging() delmail gc.collect() except: print("文本文件格式不正确")
watchpc.py
#-*-coding:utf-8-*- #Author:WuYang #Date-modified:07Nov2019 #Function:sendalarmdatathroughSMTPprotocol #Architecture:cpu.py,mem.py,etc.istomonitorperformanceofserver #Lang:Python3.7 #Env:CentOS7/WindowServer2012R2 importtime fromcpuimportmycpumonitor frommemimportmymemmonitor importgc if__name__=="__main__": whileTrue: memObj=mymemmonitor(50) memObj.mem_monitor() cpuObj=mycpumonitor(10) cpuObj.cpu_monitor() delmemObj gc.collect() time.sleep(10)
emailsender.py
#-*-coding:utf-8-*- importsmtplib importchardet importcodecs importos fromemail.mime.textimportMIMEText fromemail.headerimportHeader fromemail.mime.multipartimportMIMEMultipart #第三方SMTP服务 classtxtMail(object): def__init__(self,host=None,auth_user=None,auth_password=None): self.host="smtp.163.com"ifhostisNoneelsehost#设置发送邮件服务使用专用报警账户的用户名 self.auth_user="xxxxxx@163.com"ifauth_userisNoneelseauth_user#上线时使用专用报警账户的用户名 self.auth_password=( "xxxxxxxx"ifauth_passwordisNoneelseauth_password )#上线时使用专用报警账户的密码 self.sender="xxxxxxxx@163.com" defsend_mail(self,subject,msg_str,recipient_list,attachment_list=None): message=MIMEMultipart() message["From"]=self.sender message["To"]=Header(";".join(recipient_list),"utf-8") message["Subject"]=Header(subject,"utf-8") message.attach(MIMEText(msg_str,"plain","utf-8")) #如果有附件,则添加附件 ifattachment_list: forattinattachment_list: attachment=MIMEText(open(att,"rb").read(),"base64","utf-8") attachment["Content-Type"]="application/octet-stream" #这里filename可以任意写,写什么名字,邮件中显示什么名字 filename=os.path.basename(att) attachment.add_header( "Content-Disposition", "attachment", filename=("utf-8","",filename), ) message.attach(attachment) smtpObj=smtplib.SMTP_SSL(self.host) smtpObj.connect(self.host,smtplib.SMTP_SSL_PORT) smtpObj.login(self.auth_user,self.auth_password) smtpObj.sendmail(self.sender,recipient_list,message.as_string()) smtpObj.quit() print("邮件发送成功") print(attachment_list) defguess_chardet(self,filename): """ :paramfilename:传入一个文本文件 :return:返回文本文件的编码格式 """ encoding=None try: #由于本需求所解析的文本文件都不大,可以一次性读入内存 #如果是大文件,则读取固定字节数 raw=open(filename,"rb").read() ifraw.startswith(codecs.BOM_UTF8):#处理UTF-8withBOM encoding="utf-8-sig" else: result=chardet.detect(raw) encoding=result["encoding"] except: pass returnencoding deftxt_send_mail(self,filename,alarm): """ :paramfilename: :return: 将指定格式的txt文件发送至邮箱,txt文件样例如下 #收件人,逗号分隔 #附件,逗号分隔 """ withopen(filename,encoding=self.guess_chardet(filename))asf: lines=f.readlines() recipient_list=lines[0].strip().split(",") attachment_list=[] forfileinlines[-1].strip().split(","): ifos.path.isfile(file): attachment_list.append(file) #如果没有附件,则为None ifattachment_list==[]: attachment_list=None withopen(alarm,encoding=self.guess_chardet(alarm))asf1: lines1=f1.readlines() subject=lines1[0].strip() msg_str="".join(lines1[1:]) self.send_mail( subject=subject, msg_str=msg_str, recipient_list=recipient_list, attachment_list=attachment_list, )
test.config
XXXXX@qq.com,XXXXX@163.com libvirt.log,qemu.log
注意事项
需进入邮箱设置,开启POP3/SMTP/IMAP。
总结
以上所述是小编给大家介绍的Python实现报警信息实时发送至邮箱功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。