Python实现报警信息实时发送至邮箱功能(实例代码)

所属分类: 脚本专栏 / python 阅读数: 586
收藏 0 赞 0 分享

Python实现报警信息实时发送至邮箱功能,具体内容如下所示:

程序设计

实现代码

cpu.py

# -*- coding: utf-8 -*-
import psutil
import time
from emailsender import txtMail
from log import myloggers
import gc
class mycpumonitor():
 # up是cpu监控的阈值,默认是90%
 def __init__(self, up=None):
  self.up = 90 if up is None else up
 def cpu_monitor(self):
  cpu_percent = psutil.cpu_percent()
  now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  if cpu_percent > self.up:
   filename = 'cpu.txt'
   with open(filename, 'w') as f: # 如果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()
    del mail
    gc.collect()
   except:
    print("文本文件格式不正确")

mem.py

# -*- coding: utf-8 -*-
import psutil
import time
from emailsender import txtMail
from log import myloggers
import gc
class mymemmonitor():
 # up是内存监控的阈值,默认是90%
 def __init__(self, up=None):
  self.up = 90 if up is None else up
 def mem_monitor(self):
  mem_percent = psutil.virtual_memory()[2]
  now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  if mem_percent > self.up:
   filename = 'mem.txt'
   with open(filename, 'w') as f: # 如果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()
    del mail
    gc.collect()
   except:
    print("文本文件格式不正确")

watchpc.py

# -*- coding: utf-8 -*-
# Author: WuYang
# Date-modified: 07Nov2019
# Function: send alarm data through SMTP protocol
# Architecture: cpu.py, mem.py, etc. is to monitor performance of server
# Lang: Python3.7
# Env: CentOS7/WindowServer 2012R2
import time
from cpu import mycpumonitor
from mem import mymemmonitor
import gc
if __name__ == "__main__":
 while True:
  memObj = mymemmonitor(50)
  memObj.mem_monitor()
  cpuObj = mycpumonitor(10)
  cpuObj.cpu_monitor()
  del memObj
  gc.collect()
  time.sleep(10)

emailsender.py

#-*- coding: utf-8 -*-
import smtplib
import chardet
import codecs
import os
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
# 第三方SMTP服务
class txtMail(object):
 def __init__(self, host=None, auth_user=None, auth_password=None):
  self.host = "smtp.163.com" if host is None else host # 设置发送邮件服务使用专用报警账户的用户名
  self.auth_user = "xxxxxx@163.com" if auth_user is None else auth_user # 上线时使用专用报警账户的用户名
  self.auth_password = (
   "xxxxxxxx" if auth_password is None else auth_password
  ) # 上线时使用专用报警账户的密码
  self.sender = "xxxxxxxx@163.com"
 def send_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"))
  # 如果有附件,则添加附件
  if attachment_list:
   for att in attachment_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)
 def guess_chardet(self, filename):
  """
  :param filename: 传入一个文本文件
  :return: 返回文本文件的编码格式
  """
  encoding = None
  try:
   # 由于本需求所解析的文本文件都不大,可以一次性读入内存
   # 如果是大文件,则读取固定字节数
   raw = open(filename, "rb").read()
   if raw.startswith(codecs.BOM_UTF8): # 处理UTF-8 with BOM
    encoding = "utf-8-sig"
   else:
    result = chardet.detect(raw)
    encoding = result["encoding"]
  except:
   pass
  return encoding
 def txt_send_mail(self, filename, alarm):
  """
  :param filename:
  :return:
  将指定格式的txt文件发送至邮箱,txt文件样例如下
  # 收件人,逗号分隔
  # 附件,逗号分隔
  """
  with open(filename, encoding=self.guess_chardet(filename)) as f:
   lines = f.readlines()
  recipient_list = lines[0].strip().split(",")
  attachment_list = []
  for file in lines[-1].strip().split(","):
   if os.path.isfile(file):
    attachment_list.append(file)
  # 如果没有附件,则为None
  if attachment_list == []:
   attachment_list = None
  with open(alarm, encoding=self.guess_chardet(alarm)) as f1:
   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实现报警信息实时发送至邮箱功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

更多精彩内容其他人还在看

Python实现按学生年龄排序的实际问题详解

这篇文章主要给大家介绍了关于Python实现按学生年龄排序实际问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
收藏 0 赞 0 分享

Python开发的HTTP库requests详解

Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。Requests的哲学是以PEP 20 的习语为中心开发的,所以它比urllib更加P
收藏 0 赞 0 分享

Python网络爬虫与信息提取(实例讲解)

下面小编就为大家带来一篇Python网络爬虫与信息提取(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

在python3环境下的Django中使用MySQL数据库的实例

下面小编就为大家带来一篇在python3环境下的Django中使用MySQL数据库的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python 3.x读写csv文件中数字的方法示例

在我们日常开发中经常需要对csv文件进行读写,下面这篇文章主要给大家介绍了关于Python 3.x读写csv文件中数字的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
收藏 0 赞 0 分享

Python实现解析Bit Torrent种子文件内容的方法

这篇文章主要介绍了Python实现解析Bit Torrent种子文件内容的方法,结合实例形式分析了Python针对Torrent文件的读取与解析相关操作技巧与注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现文件内容批量追加的方法示例

这篇文章主要介绍了Python实现文件内容批量追加的方法,结合实例形式分析了Python文件的读写相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python简单实现自动删除目录下空文件夹的方法

这篇文章主要介绍了Python简单实现自动删除目录下空文件夹的方法,涉及Python针对文件与目录的读取、判断、删除等相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

简单学习Python多进程Multiprocessing

这篇文章主要和大家一起简单的学习Python多进程Multiprocessing ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Python导入模块时遇到的错误分析

这篇文章主要给大家详细解释了在Python处理导入模块的时候出现错误以及具体的情况分析,非常的详尽,有需要的小伙伴可以参考下
收藏 0 赞 0 分享
查看更多