Python之psutil模块的使用

1、psutil模块的作用:

psutil是一个开源且跨平台的库,提供获取操作的信息,如cpu、内存、磁盘、网络等信息,psutil还提供了许多命令行工具提供的功能,
包括ps,top,lsof,netstat,ifconfig,who,df,kill,free,nice,ionice,iostat,uptim,pidof,tty,taskset,pmap。非常强大!

 2、psutil模块的安装

pip install psutil

 3、获取CPU常用的信息

import psutil

# 获取CPU常用的信息
print(psutil.cpu_count())  # 获取逻辑的CPU个数
print(psutil.cpu_count(logical=False))  # 获取物理的CPU个数
print(psutil.cpu_percent())  # 获取CPU的利用率
print(psutil.cpu_percent(percpu=True))  # 获取所有逻辑CPU个数的利用率
print(psutil.cpu_percent(percpu=True, interval=2))  # 获取2秒内所有逻辑CPU个数的利用率
print(psutil.cpu_times(percpu=True))  # 查看所有CPU的时间花费
print(psutil.cpu_percent(percpu=True, interval=3))  # 查看3秒内所有CPU的时间花费的比例
print(psutil.cpu_stats())  # 查看CPU上下文切换,中断,软中断,系统调用次数

 4、获取内存常用的信息

import psutil

# 获取内存常用的信息
print(psutil.virtual_memory())  # 查看总内存、可用内存,内存利用率,buffer和cached等,除了内存利用率,其它单位是字节

def byte2human(n):
    """
    字节自动转为可读性强的函数
    :param n:字节数
    :return:
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10  # 左位移2位乘10
    for s in reversed(symbols):
        if n >= prefix[s]:  # 只在大于1000的时候,才转换为K
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return '%sB' % n
result = byte2human(psutil.virtual_memory().total)
print(result)

print(psutil.swap_memory()) #查看虚拟内存的使用情况

 5、获取磁盘的常用信息

import psutil
print(psutil.disk_partitions()) #查看磁盘名称、挂载点、文件系统的类型等信息

def get_disk_via_moutpoint(mountpoint):
    """查看硬盘挂载磁盘"""
    disk = [item for item in psutil.disk_partitions() if item.mountpoint == mountpoint]
    return disk[0].device
result = get_disk_via_moutpoint('C:\\')
print(result)

print(psutil.disk_usage('C:\\'))  # 查看硬盘的大小,已使用磁盘容量,空间利用率等
print(psutil.disk_io_counters(perdisk=True))  # 查看每个磁盘的读的次数,写的次数,读字节数,写的字节数等,省去了解析/pro/diskstats文件

 6、获取网络相关的信息

import psutil

# 获取网络相关的信息
print(psutil.net_io_counters()) #获取所有网口的所有流量和包
print(psutil.net_io_counters(pernic=True)) #获取每张网口的流量和包
print(psutil.net_connections())  # 获取每个网络连接的信息
print(psutil.net_if_addrs()) #获取网卡的配置信息
print(psutil.net_if_stats())  # 获取网卡是否启动、通信类型,MTU,传输速度等

 7、其它参数的获取

import psutil
import datetime

print(psutil.users()) # 获取用户登陆信息

print(psutil.boot_time()) #返回启动系统的时间戳
t = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S')
print(t)

8、进程管理常用方法

import psutil
import datetime
import signal

init_process = psutil.Process(11288)  # 获取linux 第一个进程
print(init_process.cmdline())  # 获取启动的程序位置
print(init_process.name())  # 获取进程名字
print(datetime.datetime.fromtimestamp(init_process.create_time()).strftime('%Y-%m-%d %H:%M:%S'))  # 获取进程启动时间
print(init_process.num_fds()) #获取文件打开个数
print(init_process.threads()) #获取子进程的个数
print(init_process.is_running())#判断进程是否运行着
init_process.send_signal(signal.SIGKILL)#发送信号给进程
init_process.kill() #发送SIGKILL信号结束进程
init_process.terminate()  # 发送SIGTERM信号结束进程

print(psutil.pids()) #获取正在运行的所在pid
print(psutil.pid_exists(1))  # 判断pid是否存在

# 迭代获取所有的进程对象
for item in psutil.process_iter():
    print(item)

9、获取一台主机的监控信息且发送邮件的示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>监控信息</title>
</head>
<body>
<table border="1">
    <tr>
        <td>服务器名称</td>
        <td>{{hostname}}</td>
    </tr>
    <tr>
        <td>开机时间</td>
        <td>{{boot_time}}</td>
    </tr>
    <tr>
        <td>CPU个数</td>
        <td>{{cpu_count}}</td>
    </tr>
    <tr>
        <td>CPU利用率</td>
        <td>{{cpu_percent}}</td>
    </tr>
    <tr>
        <td>内存总量</td>
        <td>{{mem_total}}</td>
    </tr>
    <tr>
        <td>内存利用率</td>
        <td>{{mem_percent}}</td>
    </tr>
    <tr>
        <td>内存已用空间</td>
        <td>{{mem_used}}</td>
    </tr>
    <tr>
        <td>内存可用空间</td>
        <td>{{mem_free}}</td>
    </tr>
    <tr>
        <td>磁盘空间总量</td>
        <td>{{disk_total}}</td>
    </tr>
    <tr>
        <td>磁盘空间利用率</td>
        <td>{{disk_percent}}</td>
    </tr>
    <tr>
        <td>磁盘已用空间</td>
        <td>{{disk_used}}</td>
    </tr>
    <tr>
        <td>磁盘可用空间</td>
        <td>{{disk_free}}</td>
    </tr>
</table>
</body>
</html>
index.html

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import jinja2
import socket

import psutil
import os
import yamail

def render(tpl_path, *args, **kwargs):
    """渲染html模板"""
    path, filename = os.path.split(tpl_path)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or './')
    ).get_template(filename).render(**kwargs)

def byte2human(n):
    """
    字节自动转为可读性强的函数
    :param n:字节数
    :return:
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10  # 左位移2位乘10
    for s in reversed(symbols):
        if n >= prefix[s]:  # 只在大于1000的时候,才转换为K
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return '%sB' % n

def get_cpu_info():
    """获取CPU个数和1秒内CPU的利用率"""
    cpu_count = psutil.cpu_count()
    cpu_percent = psutil.cpu_percent(interval=1)
    return dict(cpu_count=cpu_count, cpu_percent=cpu_percent)

def get_memory_info():
    """获取内存的信息"""
    virtual_mem = psutil.virtual_memory()
    mem_total = byte2human(virtual_mem.total)  # 总内存大小
    mem_percent = virtual_mem.percent  # 内存的使用率

    mem_free = byte2human(virtual_mem.free)  # 未使用内存
    mem_used = byte2human(virtual_mem.total * (virtual_mem.percent / 100))  # 使用内存
    return dict(mem_total=mem_total, mem_percent=mem_percent, mem_free=mem_free, mem_used=mem_used)

def get_disk_info():
    """获取硬盘的信息"""
    disk_usage = psutil.disk_usage('C:\\')
    disk_total = byte2human(disk_usage.total)  # 硬盘总大小
    disk_percent = disk_usage.percent  # 硬盘的使用率
    disk_free = byte2human(disk_usage.free)  # 硬盘未使用大小
    disk_used = byte2human(disk_usage.used)  # 硬盘的使用大小
    return dict(
        disk_total=disk_total,
        disk_percent=disk_percent,
        disk_free=disk_free,
        disk_used=disk_used
    )


def get_boot_info():
    """查看系统的开始时间"""
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S')
    return dict(boot_time=boot_time)


def collect_monitor_data():
    """将所有字典组合成在一起"""
    data = {}
    data.update(get_boot_info())
    data.update(get_cpu_info())
    data.update(get_disk_info())
    data.update(get_memory_info())
    return data

if __name__ == '__main__':
    email_username = 'xxx@qq.com'
    email_password = 'xxxx'
    smtp_ip = 'smtp.ym.163.com'

    RECV_EMAIL = ['xxx@qq.com']

    hostname = socket.gethostname()
    data = collect_monitor_data()
    data.update(hostname=hostname)

    content = render('index.html', **data)

    with yamail.SMTP(email_username, email_password, host=smtp_ip, port=465) as yag:
        for to_email in RECV_EMAIL:
            yag.send(to_email, subject='监控信息', contents=content)

 测试效果

 

posted @ 2020-01-20 16:01  小粉优化大师  阅读(1154)  评论(0编辑  收藏  举报