import psutil,time
class Monitor():
cpu_data=[]
@classmethod
def mem(cls,max):
val = psutil.virtual_memory().percent
print(val)
if val >50:
cls.send_msg("内存使用率为{}%,超过了{}%,请关注".format(val,max))
@classmethod
def cpu(cls,max):
val = psutil.cpu_percent(1)
cls.cpu_data.append(val)
print(cls.cpu_data)
if len(cls.cpu_data) >=3 :
avg = sum(cls.cpu_data)/len(cls.cpu_data)
if avg > max:
cls.send_msg('CPU使用率{}%过高,超过了{}%,请关注'.format(avg,max))
cls.cpu_data.pop(0)
@classmethod
def send_msg(cls,content):
print(cls,content)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
#设置smtplib所需的参数
#下面的发件人,收件人是用于邮件传输的。
#smtpserver = 'smtp.163.com'
smtpserver = 'smtp.exmail.qq.com'
username = '[email protected]'
password='xxx'
sender='[email protected]'
#receiver='[email protected]'
#收件人为多个收件人
receiver=['[email protected]','[email protected]']
subject = 'Python email test'
#通过Header对象编码的文本,包含utf-8编码信息和Base64编码信息。以下中文名测试ok
#subject = '中文标题'
#subject=Header(subject, 'utf-8').encode()
#构造邮件对象MIMEMultipart对象
#下面的主题,发件人,收件人,日期是显示在邮件页面上的。
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = '[email protected]
#msg['To'] = '[email protected]'
#收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
msg['To'] = ";".join(receiver)
#构造文字内容
#text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(content,'plain', 'utf-8')
msg.attach(text_plain)
#发送邮件
smtp = smtplib.SMTP()
#smtp.connect('smtp.163.com')
smtp.connect('smtp.exmail.qq.com')
#我们用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
#smtp.set_debuglevel(1)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
while True:
Monitor.mem(50)
Monitor.cpu(0.01)
time.sleep(5)