python库psutil简介

使用python库psutil可以获取主机的磁盘、内存、CPU等信息,具体使用案例如下:

systeminfo.py
封装函数,返回磁盘、内存、CPU、swap信息

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

from IPy import IP

class SystemInfo(object):
    """函数初始化"""

    def __init__(self):
        super().__init__()

    # 一、CPU
    def cpu_info(self):
        # CPU 物理个数
        physical_id = psutil.cpu_count(logical=False)

        # CPU 逻辑个数
        core_id = psutil.cpu_count()

        # 显示所有逻辑CPU信息
        use_rate = ("%.2f" % psutil.cpu_times().user)

        # 定义一个字典,将CPU信息写入字典中
        cpu_info = {
            'physical_id': physical_id,
            'core_id': core_id,
            'use_rate': use_rate
        }

        # 返回CPU信息的一个字典
        return cpu_info

    # 二、内存
    def mem_info(self):
        # 显示所有内存信息
        mem = psutil.virtual_memory()
        mem_total = str("%0.2f" % (mem.total / 1024 / 1024 / 1024)) + "G"
        mem_use = str("%0.2f" % (mem.used / 1024 / 1024 / 1024)) + "G"
        mem_free = str("%0.2f" % (mem.free / 1024 / 1024 / 1024)) + "G"
        mem_usage_rate = str("%0.2f" % ((mem.used / mem.total) * 100)) + "%"
        mem_info = {
            'mem_total': mem_total,
            'mem_use': mem_use,
            'mem_free': mem_free,
            'mem_usage_rate': mem_usage_rate
        }
        return mem_info

    # 三、磁盘
    def disk_info(self, disk_name):
        '''
        :param disk_name: 磁盘名字,例如linux根目录: '/',windows C盘: 'C:\\'
        :return: 磁盘大小、使用量、剩余量、使用率
        '''
        # 分区(参数)的使用情况
        # disk_name 盘使用情况
        disk = psutil.disk_usage(disk_name)
        disk_total = str("%0.2f" % (disk.total / 1024 / 1024 / 1024)) + "G"
        disk_use = str("%0.2f" % (disk.used / 1024 / 1024 / 1024)) + "G"
        disk_free = str("%0.2f" % (disk.free / 1024 / 1024 / 1024)) + "G"
        disk_usage_rate = str("%0.2f" % ((disk.used / disk.total) * 100)) + "%"
        disk_info = {
            'disk_total': disk_total,
            'disk_use': disk_use,
            'disk_free': disk_free,
            'disk_usage_rate': disk_usage_rate
        }
        return disk_info

    # 四、swap
    def swap_info(self):
        swap = psutil.swap_memory()
        swap_total = str("%0.2f" % (swap.total / 1024 / 1024 / 1024)) + "G"
        swap_use = str("%0.2f" % (swap.used / 1024 / 1024 / 1024)) + "G"
        swap_free = str("%0.2f" % (swap.free / 1024 / 1024 / 1024)) + "G"
        swap_usage_rate = str("%0.2f" % ((swap.used / swap.total) * 100)) + "%"

        swap_info = {
            'swap_total': swap_total,
            'swap_use': swap_use,
            'swap_free': swap_free,
            'swap_usage_rate': swap_usage_rate
        }

        return swap_info

    # 五、ip和主机名
    def ip_info(self):
        hostname = socket.gethostname()
        ipaddr = socket.gethostbyname(hostname)
        ip_type = IP(ipaddr).iptype()
        ip_info = {
            'hostname': hostname,
            'ipaddr': ipaddr,
            'ip_type': ip_type
        }
        return ip_info

applucationb.py
调用SystemInfo里面的函数,拼接邮件信息

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

# 创建SystemInfo实例
SYSTEM_INFO = systeminfo.SystemInfo()

# 创建一个空字典,存储所有采集信息
system_info = {}

"""
使用的元素有:
ipaddr = ""
hostname = ""
physical_id = ""
core_id = ""
use_rate = ""
mem_total = ""
mem_use = ""
mem_free = ""
mem_usage_rate = ""
disk_total = ""
disk_use = ""
disk_free = ""
disk_usage_rate = ""
"""

# sendEmail

def send_email():
    # 第三方 SMTP 服务
    mail_host = "xxx"  # 设置服务器
    mail_user = "xxx"  # 用户名
    mail_pass = "xxx"  # 口令

    sender = 'xxxt'
    receivers = ['xxx']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
    mail_msg = (
            "ip地址: %s 主机名: %s ip类型: %s" % (
        system_info.get('ipaddr'),
        system_info.get('hostname'),
        system_info.get('ip_type')
    ) +
            "\n物理CPU: %s 逻辑CPU: %s 使用比率: %s" % (
                system_info.get('physical_id'),
                system_info.get('core_id'),
                system_info.get('use_rate')
            ) +
            "\n内存大小: %s 使用内存: %s 剩余内存: %s 内存使用率: %s" % (
                system_info.get('mem_total'),
                system_info.get('mem_use'),
                system_info.get('mem_free'),
                system_info.get('mem_usage_rate')
            ) +
            "\nswap大小: %s 使用swap: %s  剩余swap: %s  swap使用率: %s " % (
                system_info.get('swap_total'),
                system_info.get('swap_use'),
                system_info.get('swap_free'),
                system_info.get('swap_usage_rate')
            ) +
            "\n磁盘大小: %s 使用磁盘: %s  剩余磁盘: %s  磁盘使用率: %s " % (
                system_info.get('disk_total'),
                system_info.get('disk_use'),
                system_info.get('disk_free'),
                system_info.get('disk_usage_rate')
            )
    )

    message = MIMEText(mail_msg, 'plain', 'utf-8')  # html类型的邮件
    message['From'] = Header("主题", 'utf-8')
    message['To'] = Header("测试", 'utf-8')

    subject = 'Python SMTP 邮件测试'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 465为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")
    finally:
        smtpObj.close()

# cpu
def cpu_info():
    cpu_info = SYSTEM_INFO.cpu_info()
    for key, value in cpu_info.items():
        if key:
            system_info[key] = value
        else:
            return

# 内存
def mem_info():
    mem_info = SYSTEM_INFO.mem_info()
    for key, value in mem_info.items():
        if key:
            system_info[key] = value
        else:
            return

# 磁盘
def disk_info(diskname):
    disk_info = SYSTEM_INFO.disk_info(diskname)
    for key, value in disk_info.items():
        if key:
            system_info[key] = value
        else:
            return

# swap
def swap_info():
    swap_info = SYSTEM_INFO.swap_info()
    for key, value in swap_info.items():
        if key:
            system_info[key] = value
        else:
            return

# ip和主机名
def ip_info():
    ip_info = SYSTEM_INFO.ip_info()
    for key, value in ip_info.items():
        if key:
            system_info[key] = value
        else:
            return

# 程序启动入口
if __name__ == '__main__':
    cpu_info()
    mem_info()
    disk_info('C:\\')  # 对应的盘符
    swap_info()
    ip_info()
    send_email()
    print(system_info)

实现效果

python库psutil简介

上一篇:3、存储管理


下一篇:n阶汉诺塔问题