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生成8位随机字符串的方法分析
Dec 05 Python
对pandas进行数据预处理的实例讲解
Apr 20 Python
Python中利用xpath解析HTML的方法
May 14 Python
Python读取指定日期邮件的实例
Feb 01 Python
使用Python实现跳帧截取视频帧
May 31 Python
在python中实现调用可执行文件.exe的3种方法
Jul 07 Python
与Django结合利用模型对上传图片预测的实例详解
Aug 07 Python
Python unittest生成测试报告过程解析
Sep 08 Python
Python 解析xml文件的示例
Sep 29 Python
利用pipenv和pyenv管理多个相互独立的Python虚拟开发环境
Nov 01 Python
详解如何使用Pytest进行自动化测试
Jan 14 Python
python树莓派通过队列实现进程交互的程序分析
Jul 04 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
关于crontab的使用详解
2013/06/24 PHP
JavaScript 入门·JavaScript 具有全范围的运算符
2007/10/01 Javascript
详解new function(){}和function(){}() 区别分析
2008/03/22 Javascript
学习ExtJS Column布局
2009/10/08 Javascript
jQuery EasyUI中对表格进行编辑的实现代码
2010/06/10 Javascript
jquery ajax请求实例深入解析
2012/11/26 Javascript
js 获取input点选按钮的值的方法
2014/04/14 Javascript
jquery禁用右键示例
2014/04/28 Javascript
jQuery+ajax实现鼠标单击修改内容的思路
2014/06/29 Javascript
JavaScript页面模板库handlebars的简单用法
2015/03/02 Javascript
详解jQuery选择器
2016/12/21 Javascript
WebSocket实现简单客服聊天系统
2017/05/12 Javascript
vue 的keep-alive缓存功能的实现
2018/03/22 Javascript
video.js 一个页面同时播放多个视频的实例代码
2018/11/27 Javascript
详解Vue源码之数据的代理访问
2018/12/11 Javascript
jquery实现弹窗(系统提示框)效果
2019/12/10 jQuery
windows如何把已安装的nodejs高版本降级为低版本(图文教程)
2020/12/14 NodeJs
Python引用类型和值类型的区别与使用解析
2017/10/17 Python
python调用OpenCV实现人脸识别功能
2018/05/25 Python
python pandas模块基础学习详解
2019/07/03 Python
python实现多进程通信实例分析
2019/09/01 Python
详解Python之Scrapy爬虫教程NBA球员数据存放到Mysql数据库
2021/01/24 Python
浅谈CSS3动画的回调处理
2016/07/21 HTML / CSS
html5 worker 实例(二) 图片变换效果
2013/06/24 HTML / CSS
小学生演讲稿
2014/01/12 职场文书
25岁生日感言
2014/01/13 职场文书
12岁生日感言
2014/01/21 职场文书
幼儿教师研修感言
2014/02/12 职场文书
简单租房协议书
2014/04/09 职场文书
入党综合考察材料
2014/06/02 职场文书
本科毕业论文答辩稿
2015/06/23 职场文书
红与黑读书笔记
2015/06/29 职场文书
商业计划书之服装
2019/09/09 职场文书
Python基础之常用库常用方法整理
2021/04/30 Python
python process模块的使用简介
2021/05/14 Python
SpringBoot整合JWT的入门指南
2021/06/29 Java/Android