Python监控服务器实现邮件微信报警[未测试]

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

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

 
  1. import psutil, time 
  2. import datetime 
  3. from wechatpy import WeChatClient 
  4. class Monitor(): 
  5.  cpu_data = [] 
  6.  @classmethod 
  7.  def mem(cls, max=90): 
  8.  val = psutil.virtual_memory().percent 
  9.  if val > max: 
  10.  cls.send_msg('内存使用率为{:1.f}%,超过了{}%,请关注'.format(val, max)) 
  11.  @classmethod 
  12.  def cpu(cls, max=90): 
  13.  val = psutil.cpu_percent(1) 
  14.  cls.cpu_data.append(val) 
  15.  if len(cls.cpu_data) >= 3: 
  16.  avg = sum(cls.cpu_data) / len(cls.cpu_data) 
  17.  if avg > max: 
  18.  cls.send_msg('CPU使用率为{:1f}%,超过了{}%,请关注'.format(avg, max)) 
  19.  cls.cpu_data.pop(0) 
  20.  @classmethod 
  21.  def send_msg(cls, content): 
  22.  cls.mail(content) 
  23.  cls.wechat(content) 
  24.  @classmethod 
  25.  def mail(cls, content): 
  26.  import smtplib 
  27.  from email.mime.text import MIMEText 
  28.  from email.utils import formataddr 
  29.  nickname = '监控程序' 
  30.  # 发送者的信息 
  31.  sender = '[email protected]
  32.  password = '*****' 
  33.  # 接收方的邮箱 
  34.  receiver = '[email protected]
  35.  msg = MIMEText(content, 'html', 'utf-8') 
  36.  msg['From'] = formataddr([nickname, sender]) 
  37.  msg['Subject'] = '自动报警' 
  38.  server = smtplib.SMTP_SSL('smtp.qq.com', 465) 
  39.  try: 
  40.  server.login(sender, password) 
  41.  server.sendmail(sender, [receiver], msg.as_string()) 
  42.  except Exception as ex: 
  43.  print(ex) 
  44.  finally: 
  45.  server.quit() 
  46.  @classmethod 
  47.  def wechat(cls, content): 
  48.  client = WeChatClient('xxxx', 'xxxx') 
  49.  template_id = 'xxxxx' 
  50.  openid = 'xxxx' 
  51.  data = { 
  52.  'msg': {"value": content, "color": "#173177"}, 
  53.  'time': {"value": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "color": "#173177"}, 
  54.  } 
  55.  try: 
  56.  client.message.send_template(openid, template_id, data) 
  57.  except Exception as ex: 
  58.  print(ex) 
  59. while True: 
  60.  Monitor.mem(90) 
  61.  Monitor.cpu(90) 
  62.  time.sleep(5) 

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

qq邮箱:

 

微信报警:

以上就是所有的代码了。

猜你喜欢

转载自my.oschina.net/u/3371661/blog/2988329