python监控服务器发邮件

# -*- coding: utf-8 -*-
# @Time    : 2018/10/8 11:33
# @Author  : wangyafeng
# @Email   : 279949848@qq.com
# @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 = 'yafengwang_85@126.com'
    password = '123456'
    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'] = 'yafengwang_85@126.com'
    # 接收邮箱
    msg['to'] = '305100277@qq.com'
    # 发送主题
    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




######################################上面有个bug,无法进行群发 so变更后的代码如下#############################
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', "XXXXXXX" #,这个XXXX是发件地址生成的访问授权码
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 @ 2019-12-30 10:01  王亚锋  阅读(331)  评论(0编辑  收藏  举报