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

 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)  #windows
12 #ip_address=os.popen("ifconfig | grep 'inet ' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $2}' | head -1").read()    #linux下获取IP
13 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

################################解决无法群发邮件的问题#######################
def get_test_filename():
    '''获取最近生成的报告'''
    base_dir="./"
    l=os.listdir(base_dir)
    l.sort(key=lambda fn:os.path.getatime(base_dir+fn) if not os.path.isdir(base_dir+fn) else 0)
    filename=str(l[-1])
    return  filename


def sendemail():
    url="http://192.168.0.166:9090/"+get_test_filename()
    smt_p = smtplib.SMTP()
    smt_p.connect(host='smtp.126.com', port=25)
    sender, password = 'mantis_jidian@126.com', "ZCPYDBLKWEYDMZRW"   #采用mantis的发送邮件地址
    smt_p.login(sender, password)
    receiver_addresses, count_num = ['279949848@qq.com', 'yafengwang_85@126.com'], 1
    for email_address in receiver_addresses:
        try:
            msg = multipart.MIMEMultipart()
            msg['From'] = "王亚锋"
            msg['To'] = email_address
            msg['subject'] = header.Header('测试结果', 'utf-8')
            msg.attach(text.MIMEText('本次测试结果查看地址是:'+url, 'plain', 'utf-8'))
            smt_p.sendmail(sender, email_address, msg.as_string())
            time.sleep(10)
            print('第%d次发送给%s' % (count_num, email_address))
            count_num = count_num + 1
        except Exception as e:
            print('第%d次给%s发送邮件异常' % (count_num, email_address))
            continue
    smt_p.quit()

 

 

 

posted @ 2018-10-11 09:17  王亚锋  阅读(277)  评论(0编辑  收藏  举报