监控本机CPU内存及IO 发邮件

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2018/10/8 11:33
 3 # @Author  : wangyafeng
 4 # @Email   : [email protected]
 5 # @Software: PyCharm
 6 import psutil,socket,uuid,time
 7 from email.mime.text import MIMEText
 8 import platform,time,smtplib
 9 
10 host_name=socket.gethostname()
11 ip_address=socket.gethostbyname(host_name)
12 data_time = str(time.strftime("%Y%m%d", time.localtime(int(time.time()))))
13 my_time = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))))
14 
15 
16 def get_mac_address():
17     mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
18     return ":".join([mac[e:e+2] for e in range(0,11,2)])
19 
20 
21 with open(data_time, "a+",encoding="utf-8") as f:
22     f.write("电脑名字:" + str(host_name)+"\t"+"IP:"+str(ip_address)+"\t"+"mac地址:"+str(get_mac_address())+"\n")
23     f.flush()
24     f.close()
25 
26 
27 def sendemail():
28     smtpserver = 'smtp.126.com'
29     user = '[email protected]'
30     password = 'XXXXXXXX'
31     msg = MIMEText(
32         platform.node() + '时间:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + ''+"\n"+str(ip_address)+'异常', 'html',
33         'utf-8')
34     # 发送邮箱
35     msg['from'] = '[email protected]'
36     # 接收邮箱
37     msg['to'] = '[email protected]'
38     # 发送主题
39     sbuject = '请检查服务器'
40     try:
41         # 链接发送邮件
42         smtp = smtplib.SMTP()
43         smtp.connect(smtpserver)
44         smtp.login(user, password)
45         smtp.sendmail(msg['from'], msg['to'], msg.as_string())
46         print("邮件发送完毕!")
47         smtp.quit()
48     except smtplib.SMTPException:
49         print("发送邮件失败!")
50 
51 
52 while True:
53     with open(data_time, "a+",encoding="utf-8") as f:
54         f.flush()
55         if psutil.cpu_percent(percpu=False,interval=10)>5 or psutil.virtual_memory().percent>50:
56             f.write(my_time+"\t"+"cpu:"+str(psutil.cpu_percent(percpu=False, interval=10))+"\t"+"\t"+"内存:"+str(psutil.virtual_memory().percent)+"\t"+"\t"+"net_io:"+str(psutil.net_io_counters()) + "\n")
57             f.flush()
58             sendemail()
59         else:
60             pass

猜你喜欢

转载自www.cnblogs.com/wangyafeng/p/9770589.html