# -*- coding: utf-8 -*- # @Time : 2018/10/8 11:33 # @Author : wangyafeng # @Email : [email protected] # @Software: PyCharm import psutil,socket,uuid,time from email.mime.text import MIMEText import platform,time,smtplib host_name=socket.gethostname() ip_address=socket.gethostbyname(host_name) #windows #ip_address=os.popen("ifconfig | grep 'inet ' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $2}' | head -1").read() #linux下获取IP data_time = str(time.strftime("%Y%m%d", time.localtime(int(time.time())))) def get_mac_address(): mac=uuid.UUID(int = uuid.getnode()).hex[-12:] return ":".join([mac[e:e+2] for e in range(0,11,2)]) with open(data_time, "a+",encoding="utf-8") as f: f.write("电脑名字:" + str(host_name)+"\t"+"IP:"+str(ip_address)+"\t"+"mac地址:"+str(get_mac_address())+"\n") f.flush() def sendemail(): smtpserver = 'smtp.126.com' user = '[email protected]' password = 'wyf778WYF778' msg = MIMEText( platform.node() + '时间:' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) + ''+"\n"+str(ip_address)+'异常', 'html', 'utf-8') # 发送邮箱 msg['from'] = '[email protected]' # 接收邮箱 msg['to'] = '[email protected]' # 发送主题 sbuject = '请检查服务器' try: # 链接发送邮件 smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user, password) smtp.sendmail(msg['from'], msg['to'], msg.as_string()) print("邮件发送完毕!") smtp.quit() except smtplib.SMTPException: print("发送邮件失败!") while True: with open(data_time, "a+",encoding="utf-8") as f: my_time = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))) #mytime=str(datetime.datetime.now())[:19] #另外一种获取时间方法 if psutil.cpu_percent(percpu=False,interval=1)>5 or psutil.virtual_memory().percent>50: 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") f.flush() sendemail() else: pass