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

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

 本文中笔者暂时实现的只有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(avgmax)) 
  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 = 'xxx@qq.com' 
  32.  password = '*****' 
  33.  # 接收方的邮箱 
  34.  receiver = 'aa@bb.cc' 
  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邮箱:

 

微信报警: 

以上就是所有的代码了。

责任编辑:武晓燕 来源: 黑白之道
相关推荐

2011-03-22 09:07:13

Nagios监控Linux

2012-02-23 23:46:26

2014-01-02 15:16:42

PythonLinux服务器服务器监控

2011-03-25 15:24:40

Nagios监控

2016-09-30 13:48:25

UbuntuPython报警系统

2012-06-26 12:14:05

容错服务器stratus

2009-09-02 14:23:19

邮件服务器性

2009-09-01 11:18:26

邮件服务器

2009-09-02 14:43:26

邮件服务器

2009-09-02 14:01:50

邮件服务器

2014-09-29 16:52:00

2009-09-02 14:34:42

邮件服务器

2009-09-02 14:27:29

邮件服务器

2009-08-20 10:19:27

故障服务器自动报警

2012-02-21 09:59:52

2011-02-21 14:12:15

Postfix服务器安装

2009-09-02 17:25:02

邮件服务器

2010-06-02 16:48:49

postfix邮件服务

2015-08-25 15:34:51

2011-03-23 10:17:26

点赞
收藏

51CTO技术栈公众号