用python实现监控cpu、内存、硬盘、网卡流量并发邮件报警

import psutil
import smtplib
from email.mime.text import MIMEText
from email.header import Header


def cpu_info():
    cpu = psutil.cpu_percent(1)  # 一秒内cpu使用率,单位
    cpu_per = '%.2f%%' % cpu     # 变成百分数,保留两位小数
    return cpu_per


def mem_info():
    mem = psutil.virtual_memory()
    mem_per = '%.2f%%' % mem[2]
    mem_total = str(int(mem[0] / 1024 / 1024)) + 'M'
    mem_used = str(int(mem[3] / 1024 / 1024)) + 'M'
    mem_dict = {
        'mem_per': mem_per,
        'mem_total': mem_total,
        'mem_used': mem_used,
    }
    return mem_dict


# C盘利用率
def disk_info():
    c_info = psutil.disk_usage("C:")
    c_per = '%.2f%%' % c_info[3]
    return c_per


def network_info():
    net = psutil.net_io_counters()
    net_sent = str(int(net[0]/1024/1024)) + 'MB'
    net_rece = str(int(net[1]/1024/1024)) + 'MB'
    net_dict = {
        'net_cent': net_sent,
        'net_rece': net_rece
    }
    return net_dict


def send_mail(message):
    sender = '[email protected]'   # 发送邮箱
    receiver = ['[email protected]']   #接收邮箱
    subject = '报警'
    username = '[email protected]'    #发送邮箱
    password = 'yourpassword'       #发送邮箱密码或授权码
    msg = MIMEText(message, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = 'Tom'
    msg['To'] = "[email protected]"
    smtp = smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()


def main():
    cpu = cpu_info()
    mem = mem_info()
    disk = disk_info()
    net = network_info()
    mes = '''
    cpu使用率:%s
    ============
    内存使用率:%s
    总内存:%s
    使用内存:%s
    ============
    C盘使用率:%s
    ============
    网卡发送流量:%s
    网卡接收流量:%s
    ''' % (cpu, mem.get('mem_per'), mem.get('mem_total'), mem.get('mem_used'), disk, net.get('net_cent'), net.get('net_rece'))
    # 检测是否到阈值
    if (cpu[:4]) > '60' or (mem.get('mem_per')[:4]) > '60' or (disk[:4] > '60'):
        send_mail(mes)
    else:
        print("没到阈值")


if __name__ == '__main__':
    main()


你可能感兴趣的:(linux,windows,python)