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

2 篇文章 0 订阅
1 篇文章 0 订阅
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 = 'your@163.com'   # 发送邮箱
    receiver = ['your@126.com']   #接收邮箱
    subject = '报警'
    username = 'your@163.com'    #发送邮箱
    password = 'yourpassword'       #发送邮箱密码或授权码
    msg = MIMEText(message, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = 'Tom<your@163.com>'
    msg['To'] = "your@126.com"
    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()


  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值