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


Posted in Python onNovember 11, 2019

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

程序设计

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 相关文章推荐
使用python实现baidu hi自动登录的代码
Feb 10 Python
Python使用redis pool的一种单例实现方式
Apr 16 Python
python制作抖音代码舞
Apr 07 Python
使用Python检测文章抄袭及去重算法原理解析
Jun 14 Python
Python 实现自动导入缺失的库
Oct 29 Python
爬虫代理池Python3WebSpider源代码测试过程解析
Dec 20 Python
python 实现将Numpy数组保存为图像
Jan 09 Python
Python实现投影法分割图像示例(一)
Jan 17 Python
Python3监控windows,linux系统的CPU、硬盘、内存使用率和各个端口的开启情况详细代码实例
Mar 18 Python
Python中如何引入第三方模块
May 27 Python
Python更改pip镜像源的方法示例
Dec 01 Python
python+opencv实现目标跟踪过程
Jun 21 Python
详解Anconda环境下载python包的教程(图形界面+命令行+pycharm安装)
Nov 11 #Python
Python序列化与反序列化pickle用法实例
Nov 11 #Python
详解Python可视化神器Yellowbrick使用
Nov 11 #Python
安装Pycharm2019以及配置anconda教程的方法步骤
Nov 11 #Python
详解Python中打乱列表顺序random.shuffle()的使用方法
Nov 11 #Python
基于Python实现ComicReaper漫画自动爬取脚本过程解析
Nov 11 #Python
Python多继承以及MRO顺序的使用
Nov 11 #Python
You might like
BBS(php & mysql)完整版(八)
2006/10/09 PHP
PHP面向对象之后期静态绑定功能介绍
2015/05/18 PHP
php pthreads多线程的安装与使用
2016/01/19 PHP
PHP的压缩函数实现:gzencode、gzdeflate和gzcompress的区别
2016/01/27 PHP
php的闭包(Closure)匿名函数初探
2016/02/14 PHP
各种快递查询--Api接口
2016/04/26 PHP
jQuery 绑定事件到动态创建的元素上的方法实例
2013/08/18 Javascript
分享9个最好用的JavaScript开发工具和代码编辑器
2015/03/24 Javascript
JS组件Bootstrap Table使用方法详解
2016/02/02 Javascript
jQuery实现滚动鼠标放大缩小图片的方法(附demo源码下载)
2016/03/05 Javascript
用JS中split方法实现彩色文字背景效果实例
2016/08/24 Javascript
JS实现表单验证功能(验证手机号是否存在,验证码倒计时)
2016/10/11 Javascript
关于vue v-for循环解决img标签的src动态绑定问题
2018/09/18 Javascript
layui 实现自动选择radio单选框(checked)的方法
2019/09/03 Javascript
微信小程序点击顶部导航栏切换样式代码实例
2019/11/12 Javascript
python with statement 进行文件操作指南
2014/08/22 Python
Python正则表达式教程之一:基础篇
2017/03/02 Python
Python中字典(dict)合并的四种方法总结
2017/08/10 Python
Python2中文处理纪要的实现方法
2018/03/10 Python
Python获取昨天、今天、明天开始、结束时间戳的方法
2018/06/01 Python
Centos 升级到python3后pip 无法使用的解决方法
2018/06/12 Python
python3使用print打印带颜色的字符串代码实例
2019/08/22 Python
python 实现矩阵按对角线打印
2019/11/29 Python
PySide2出现“ImportError: DLL load failed: 找不到指定的模块”的问题及解决方法
2020/06/10 Python
美国时尚在线:Showpo
2017/09/08 全球购物
医学检验专业大学生求职信
2013/11/18 职场文书
促销活动总结范文
2014/04/30 职场文书
财务人员个人工作总结
2015/02/27 职场文书
个人工作保证书
2015/02/28 职场文书
素质拓展训练感想
2015/08/07 职场文书
2016学习全国教书育人楷模先进事迹心得体会
2016/01/21 职场文书
python数据分析之用sklearn预测糖尿病
2021/04/22 Python
深入详解JS函数的柯里化
2021/06/09 Javascript
船舶调度指挥系统——助力智慧海事
2022/02/18 无线电
nginx日志格式分析和修改
2022/04/28 Servers
详解Redis的三种常用的缓存读写策略步骤
2022/05/06 Redis