1 # -*- coding: utf-8 -*- 2 # @Time : 2018/10/8 11:33 3 # @Author : wangyafeng 4 # @Email : 279949848@qq.com 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) #windows12 #ip_address=os.popen("ifconfig | grep 'inet ' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $2}' | head -1").read() #linux下获取IP13 data_time = str(time.strftime("%Y%m%d", 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 25 26 def sendemail():27 smtpserver = 'smtp.126.com'28 user = 'yafengwang_85@126.com'29 password = 'XXXXXXXXX'30 msg = MIMEText(31 platform.node() + '时间:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + ''+"\n"+str(ip_address)+'异常', 'html',32 'utf-8')33 # 发送邮箱34 msg['from'] = 'yafengwang_85@126.com'35 # 接收邮箱36 msg['to'] = '305100277@qq.com'37 # 发送主题38 sbuject = '请检查服务器'39 try:40 # 链接发送邮件41 smtp = smtplib.SMTP()42 smtp.connect(smtpserver)43 smtp.login(user, password)44 smtp.sendmail(msg['from'], msg['to'], msg.as_string())45 print("邮件发送完毕!")46 smtp.quit()47 except smtplib.SMTPException:48 print("发送邮件失败!")49 50 51 while True:52 with open(data_time, "a+",encoding="utf-8") as f:53 my_time = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))))54 #mytime=str(datetime.datetime.now())[:19] #另外一种获取时间方法55 if psutil.cpu_percent(percpu=False,interval=1)>5 or psutil.virtual_memory().percent>50:56 f.write(my_time+"\t"+"cpu:"+str(psutil.cpu_percent(percpu=False))+"\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