#coding:utf8
from email.mime.text import MIMEText
import smtplib,psutil,time,os,datetime


destination = ["[email protected]"] #定义邮件接收者
source = "[email protected]" #定义邮件发送者
mail_server = 'smtp.qq.com'
username = '775465751'
password = 'wrromyiywqijbdia'


def send_mail(des,title,content):
    csj = MIMEText(content)
    csj['Subject'] = title
    csj['From'] = source
    csj['To'] = ';'.join(destination)
    try:
        a = smtplib.SMTP_SSL(mail_server,465)
        a.connect(mail_server)
        a.login(username,password)
        a.sendmail(source,destination,csj.as_string())
        a.close()
        return True
    except Exception,e:
        print e
        return False


def hostname():
    com = 'hostname'
    res = os.popen(com)
    content = res.read()
    return content


def mem_use():
    total_mem = psutil.virtual_memory().total
    free_mem = psutil.virtual_memory().available
    res = (psutil.virtual_memory().available/float(psutil.virtual_memory().total))*100
    return res


def system(a,b):
    cpu_info = []
    mem_info = []
    now_time = "Date %s"%datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d")
    count = 1
    print "Start monitoring "
    while True:
        time.sleep(60) #定义采集系统信息的频率,单位为秒
        if count <= 10: #定义每采集十次系统信息后输出平均值
            cpu_info.append(psutil.cpu_percent())
            mem_info.append(mem_use())
            count += 1
        else:
            cpu_info.pop(0)
            mem_info.pop(0)
            cpu_info.append(psutil.cpu_percent())
            mem_info.append(mem_use())
            cpu_avg = sum(cpu_info)/10
            mem_avg = sum(mem_info)/10
            if (cpu_avg >= a) or (mem_avg >= b):
                print("---------------------------------------------------------")
                print now_time
                warning_cpu = ("Warning CPU Used:%.2f%%")%cpu_avg
                warning_mem = ("Warning CPU Used:%.2f%%")%mem_avg
                print warning_cpu
                print warning_mem
                send_mail(destination,"Warning Server Overload",hostname()) #发送邮件,格式为:(目的,标题,正文)
            else:
                print now_time
                print("---------------------------------------------------------")
                print("Info,CPU Used:%.2f%%")%cpu_avg
                print("Info,Memory Used:%.2f%%")%mem_avg
system(0,0) #这两个0代表设置cpu和内存的阈值,前者为CPU,后者为内存