通过Python脚本监控linux系统的状态

通过Python脚本监控linux系统的状态,第1张

import smtplib
from email.header import Header
from email.mime.text import MIMEText
import os
import time
import re
import socket
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import psutil  # python -m pip install --upgrade pip -i https://pypi.douban.com/simple


import psutil
import datetime

def send_email_smtp(content):
    host_name = 'smtp.QQ.com'
    port = 465
    sender = '1160394417@qq.com'
    receiver = '1160394417@qq.com'
    password = 'luetojqrhyffgcgf'
    msg = MIMEText(content)  # 邮件主体
    # msg['From'] = Header(sender, 'utf-8')
    # msg['TO'] = Header(receiver, 'utf-8')
    msg['From'] = sender
    msg['TO'] = receiver
    msg['subject'] = Header('监控linux系统的状态', 'utf-8')
    try:
        smtp = smtplib.SMTP_SSL(host_name, port)
        smtp.login(sender, password)
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
        print('[+]发送出')
    except Exception as err:
        print('[-]发送失败,原因:', err)

if __name__ == '__main__':
    '''内存使用率'''
    free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
    total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
    memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
    # print("物理内存: %s G" % total)
    # print("剩余物理内存: %s G" % free)
    # print("物理内存使用率: %s %%" % int(memory * 100))
    # print("系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))
    cpuQd=datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    '''硬盘使用率'''
    disk = psutil.disk_partitions()
    for i in disk:
        disk_use = psutil.disk_usage(i.mountpoint)
       # print('磁盘:{},分区格式:{}'.format(i.device, i.fstype))
       # print('使用了:{}M,空闲:{}M,总共:{}M,使用率:{}% '.format(disk_use.used / 1024 / 1024, disk_use.free / 1024 / 1024, disk_use.total / 1024 / 1024, disk_use.percent))
    '''网络流量采集'''
    net = psutil.net_io_counters()
    #print('网卡接收流量 {:.2f} Mb,网卡发送流量 {:.2f}Mb'.format(net.bytes_recv / 1024 / 1024, net.bytes_sent / 1024 / 1024))
    content = '[+]内存使用率: {}\n' \
               '[+]物理内存:{}\n' \
               '[+]剩余物理内存:{}\n' \
               '[+]系统启动时间:{}\n' \
               '[+]硬盘使用率:{}\n' \
               '[+]网络流量采集:{}\n'.format(free, total, memory, cpuQd, disk, net)
    print(content)


    send_email_smtp(content=content)
 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/785819.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-04
下一篇2022-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存