Skip to main content
德胜云
  万速智能9 > 云服务器

Python监控服务器实现邮件微信报警

2022-11-11 20:00:52 浏览:

Python监控服务器实现邮件微信报警

 本文中笔者暂时实现的只有cpu和内存的监控,Python可以监控许多的主机信息,网络,硬盘,机器状态等,以下是代码的实现,代码可以实现windowslinux的监控。

实验环境:Ubuntu16.04和windos10,python3.6.6

复制import psutil, time import datetime  from wechatpy import WeChatClient  class Monitor():   cpu_data = []   @classmethod   def mem(cls, max=90):   val = psutil.virtual_memory().percent   if val > max:   cls.send_msg(内存使用率为{:1.f}%,超过了{}%,请关注.format(val, max))   @classmethod   def cpu(cls, max=90):   val = psutil.cpu_percent(1)   cls.cpu_data.append(val)   if len(cls.cpu_data) >= 3:   avg = sum(cls.cpu_data) / len(cls.cpu_data)   if avg > max:   cls.send_msg(CPU使用率为{:1f}%,超过了{}%,请关注.format(avg, max))   cls.cpu_data.pop(0)   @classmethod   def send_msg(cls, content):   cls.mail(content)   cls.wechat(content)   @classmethod   def mail(cls, content):   import smtplib   from email.mime.text import MIMEText   from email.utils import formataddr   nickname = 监控程序  # 发送者的信息   sender = xxx@qq.com  password = *****  # 接收方的邮箱   receiver = aa@bb.cc  msg = MIMEText(content, html, utf-8)   msg[From] = formataddr([nickname, sender])   msg[Subject] = 自动报警  server = smtplib.SMTP_SSL(smtp.qq.com, 465)   try:   server.login(sender, password)   server.sendmail(sender, [receiver], msg.as_string())   except Exception as ex:   print(ex)   finally:   server.quit()   @classmethod   def wechat(cls, content):   client = WeChatClient(xxxx, xxxx)   template_id = xxxxx  openid = xxxx  data = {   msg: {"value": content, "color": "#173177"},   time: {"value": datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S), "color": "#173177"},   }   try:   client.message.send_template(openid, template_id, data)   except Exception as ex:   print(ex)  while True:   Monitor.mem(90)   Monitor.cpu(90)   time.sleep(5)  1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.

下面是qq邮箱和微信实现报警的图片:

qq邮箱:

 

微信报警: 

以上就是所有的代码了。

Python监控服务器实现邮件微信报警

  • 学会了吗「手机游戏服务器搭建教程,台州BGP服务器租用180
  • 全程干货「如何部署自己的gpu服务器?」gpu服务器搭建gp
  • 深度揭秘「批量查询ip对应域名、备案信息、百度权重」批量查询
  • 干货分享「Python快速实现一个域名、IP信息聚合网站」P
  • 速看「NVIDIA Triton 系列文章(5):安装服务器