python 监控报警-初级

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 = 'xxx@xxx.com'
         password='xxx'
         sender='xxx@xxx.com'
         #receiver='XXX@126.com'
         #收件人为多个收件人
         receiver=['xxx@xxx.com','xxx@xxx.com']

         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'] = 'xxx@xxx.com <xxx@xxx.com>'
         #msg['To'] = 'XXX@126.com'
         #收件人为多个收件人,通过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)
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值