| 
                         本文中笔者暂时实现的只有cpu和内存的监控,python可以监控许多的主机信息,网络,硬盘,机器状态等,以下是代码的实现,代码可以实现windows和linux的监控。 
实验环境: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) 
 
  
下面是qq邮箱和微信实现报警的图片: 
qq邮箱: 
   
微信报警: 
  
以上就是所有的代码了。 
【编辑推荐】 
    - 用 Python 快速实现 HTTP 和 FTP 服务器
 
    - 中标中国人民银行,曙光八路服务器再获认可
 
    - 代理服务器和Web服务器通信中的504问题
 
    - CentOS系统下PXE服务器的搭建与部署
 
    - 详解X86服务器虚拟化的资源划分和性能优化
 
 
【责任编辑:武晓燕 TEL:(010)68476606】 
            
             
            点赞 0                        (编辑:52站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |