本文中筆者暫時實現的只有cpu和內存的監控,python能夠監控許多的主機信息,網絡,硬盤,機器狀態等,如下是代碼的實現,代碼能夠實現windows和linux的監控。html
實驗環境:Ubuntu16.04和windos10,python3.6.6python
![](http://static.javashuo.com/static/loading.gif)
- 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郵箱和微信實現報警的圖片:linux
qq郵箱:windows
![](http://static.javashuo.com/static/loading.gif)
微信報警:微信
![](http://static.javashuo.com/static/loading.gif)
以上就是全部的代碼了。網絡