栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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)
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/834981.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号