Python psutil 模块

Python psutil 模块

  psutil是一个跨平台库,可以获取系统的运行进程和系统利用的资源(CPU、内存、磁盘、网络)等信息。他主要应用于系统监控,分析和限制系统资源及进程管理。他实现了同等工具提供的功能,如ps,top,lsof,netstat,ifconfig,who,df,kill,free,nice,ionice,iostat,iotop,uptime,pidof,tty,taskset,pmap等。支持32位与64位的linux,windos,os x,freeb sd,sun solaris 操作系统。

 

CPU 详情


查看cpu所有信息

>> psutil.cpu_times()
scputimes(user=11677.09, nice=57.93, system=148675.58, idle=2167147.79, iowait=260828.48, irq=7876.28, softirq=0.0, steal=3694.59, guest=0.0, guest_nice=0.0)

查看cpu所有逻辑信息

>>> psutil.cpu_times(percpu=True)
[scputimes(user=11684.17, nice=57.93, system=148683.01, idle=2168982.08, iowait=260833.18, irq=7882.35, softirq=0.0, steal=3697.3, guest=0.0, guest_nice=0.0)]

查看用户cpu时间比

>>> psutil.cpu_times().user
11684.4

查看cpu逻辑个数

>>> psutil.cpu_count()
1

查看cpu物理个数

>>> psutil.cpu_count()
1

示例:

# t1 cpu时间
cpu_user1 = psutil.cpu_times()
# 间隔时间
time.sleep(1)
# t2 cpu时间
cpu_user2 = psutil.cpu_times()

# 用户使用CPU时间
t1_user = cpu_user1.user
t2_user = cpu_user2.user

# CPUnice为负值的进程占用cpu时间
t1_nice = cpu_user1.nice
t2_nice = cpu_user2.nice

# 系统内核使用cpu时间
t1_system = cpu_user1.system
t2_system = cpu_user2.system

# 系统启动到现在除了iowait外的等待CPU时间
t1_idle = cpu_user1.idle
t2_idle = cpu_user2.idle

# CPUio磁盘io等待时间
t1_iowait = cpu_user1.iowait
t2_iowait = cpu_user2.iowait

# 通过中断硬件消耗的cpu时间
t1_irq = cpu_user1.softirq
t2_irq = cpu_user2.softirq

# 通过中断软件消耗的cpu时间
t1_steal = cpu_user1.steal
t2_steal = cpu_user2.steal

# 通过内核控制操作系统的虚拟环境的cpu使用时间
t1_guest = cpu_user1.guest
t2_guest = cpu_user2.guest

# 通过内核控制操作系统的虚拟环境CPUnice值为负数的进程使用时间
t1_guest_nice = cpu_user1.guest_nice
t2_guest_nice = cpu_user2.guest_nice

# CPU总时间
t1_total = t1_user + t1_nice + t1_system + t1_idle + \
    t1_iowait + t1_irq + t1_steal + t1_guest + t1_guest_nice
t2_total = t2_user + t2_nice + t2_system + t2_idle + \
    t2_iowait + t2_irq + t2_steal + t2_guest + t2_guest_nice

# CPU非空闲时间
t1_busy = t1_total - t1_idle
t2_busy = t2_total - t2_idle

# t1-t2 总使用时间
cpu_total = t2_total - t1_total
print(cpu_total)

# t1-t2 idle 总非空闲时间
cpu_busy = t2_busy - t1_busy
print(cpu_busy)

# t1-t2 总使用率
cpu_usage_rate = (cpu_busy / cpu_total) * 100
print(cpu_usage_rate)

# t1-t2 user 使用率
t1t2_user = t2_user - t1_user
cpu_user = (t1t2_user / cpu_total) * 100
print(cpu_user)

# t1-t2 nice 使用率
t1t2_nice = t2_nice - t1_nice
cpu_nice = (t1t2_nice / cpu_total) * 100
print(cpu_nice)

# t1-t2 system 使用率
t1t2_system = t2_system - t1_system
cpu_system = (t1t2_system / cpu_total) * 100
print(cpu_system)

# t1-t2 iowait 使用率
t1t2_iowait = t2_iowait - t1_iowait
cpu_iowait = (t1t2_iowait / cpu_total) * 100
print(cpu_iowait)

# t1-t2 irq 使用率
t1t2_irq = t2_irq - t1_irq
cpu_irq = (t1t2_irq / cpu_total) * 100
print(cpu_irq)

# t1-t2 steal 使用率
t1t2_steal = t2_steal - t1_steal
cpu_steal = (t1t2_steal / cpu_total) * 100
print(cpu_steal)

# t1-t2 guest 使用率
t1t2_guest = t2_guest - t1_guest
cpu_guest = (t1t2_guest / cpu_total) * 100
print(cpu_guest)

# t1-t2 guest_nice 使用率
t1t2_guest_nice = t2_guest_nice - t1_guest_nice
cpu_guest_nice = (t1t2_guest_nice / cpu_total) * 100
print(cpu_guest_nice)

内存详情


查看系统内存

>>> mem = psutil.virtual_memory()
>>> mem
#系统内存的所有信息
svmem(total=1040662528, available=175054848, percent=83.2, used=965718016, free=74944512, active=566755328, inactive=59457536, buffers=9342976, cached=90767360)

系统总计内存

>>> mem.total
1040662528

系统已经使用内存

>>> mem.used
965718016

示例:

# 所有内存参数
mem = psutil.virtual_memory()

# 内存总大小
mem_total = str(mem.total/1024/1024) + " MB"
print(mem_total)

# 内存使用大小
mem_used = str(mem.used/1024/1024) + " MB"
print(mem_used)

# 内存真实剩余大小
mem_free = str(mem.free/1024/1024) + " MB"
print(mem_free)

# 内存程序认为可使用大小包含缓存缓冲
mem_active = str(mem.active/1024/1024) + " MB"
print(mem_active)

# 未使用内存不包含缓存
mem_inactive = str(mem.inactive/1024/1024) + " MB"
print(mem_inactive)

# 缓冲区使用内存
mem_buffers = str(mem.buffers/1024/1024) + " MB"
print(mem_buffers)

# 未使用内存不包含缓存
mem_cached = str(mem.cached/1024/1024) + " MB"
print(mem_cached)

SWAP详情


获取swap内存信息

>>> psutil.swap_memory()
sswap(total=0, used=0, free=0, percent=0, sin=0, sout=0)

示例:

# 交换分区信息
swap_mess = psutil.swap_memory()
print(swap_mess)

# 交换分区总大小
swap_total = swap_mess.total
print("交换分区总大小:", swap_total)

# 交换分区已使用大小
swap_used = swap_mess.used
print("交换分区已使用大小:", swap_used)

# 交换分区剩余大小
swap_free = swap_mess.free
print("交换分区剩余大小:", swap_free)

# 系统从磁盘累计换入的字节数
swap_sin = swap_mess.sin
print("系统从磁盘累换入的字节数:", swap_sin)

# 系统从磁盘累计换出的字节数
swap_sout = swap_mess.sout
print("交换分区总大小:", swap_sout)

磁盘详情


读取盘参数

磁盘利用率使用psutil.disk_usage方法获取,

磁盘IO信息包括read_count(读IO数),write_count(写IO数)
read_bytes(IO写字节数),read_time(磁盘读时间),write_time(磁盘写时间),这些IO信息用

psutil.disk_io_counters()

获取磁盘的完整信息

psutil.disk_partitions()

获取分区表的参数

psutil.disk_usage('/')   #获取/分区的状态

获取硬盘IO总个数

psutil.disk_io_counters()

获取单个分区IO个数

psutil.disk_io_counters(perdisk=True)    #perdisk=True参数获取单个分区IO个数

读取网络信息

网络信息与磁盘IO信息类似,涉及到几个关键点,包括byes_sent(发送字节数),byte_recv=xxx(接受字节数),
pack-ets_sent=xxx(发送字节数),pack-ets_recv=xxx(接收数据包数),这些网络信息用

获取网络总IO信息

psutil.net_io_counters()  

磁盘容量示例:

# 输出当前分区挂载详情
disk_partitions = psutil.disk_partitions()
# 循环列表
for i in disk_partitions:
    # 分区设备名称
    print(i[0])
# 分区挂载点 print(i[1])
# 分区格式类型 print(i[2])
# 分区所属权限 print(i[3]) # 指定挂载分区大小 disk_usage = psutil.disk_usage('/') # 挂载磁盘总大小 disk_total = str(disk_usage.total/1024/1024/1024) + " GB" print(disk_total) # 挂载磁盘使用空间 disk_used = str(disk_usage.used/1024/1024/1024) + " GB" print(disk_used) # 挂载磁盘剩余空间 disk_free = str(disk_usage.free/1024/1024/1024) + " GB" print(disk_free)

磁盘IO示例:

# 磁盘io信息
diskio = psutil.disk_io_counters()
print(diskio)
# 系统每块物理磁盘io的返回信息 diskio2 = psutil.disk_io_counters(perdisk=True) print(diskio2) # 磁盘io读取次数 ioread_count = diskio.read_count print(ioread_count) # 磁盘io写入次数 iowrite_count = diskio.write_count print(iowrite_count) # 读取所有io数量 ioread_bytes = diskio.read_bytes print(ioread_bytes) # 写入所有io数量 iowrite_bytes = diskio.write_bytes print(iowrite_bytes) # 读取io时间 ioread_time = diskio.read_time print(ioread_time) # 写入io时间 iowrite_time = diskio.write_time print(iowrite_time) # 合并读取次数 ioread_merged_count = diskio.read_count print(ioread_merged_count) # 合并写入次数 iowrite_merged_count = diskio.write_count print(iowrite_merged_count) # 实际做I/O操作时间 iobusy_time = diskio.busy_time print(iobusy_time)# 两个时间段的磁盘信息 t1_io = psutil.disk_io_counters() time.sleep(1) t2_io = psutil.disk_io_counters() # 求出每秒磁盘IO的读写输出 bytes 为单位 read_bytes = str(t2_io.read_bytes - t1_io.read_bytes) + " bytes" write_bytes = str(t2_io.write_bytes - t1_io.write_bytes) + " bytes" # 求出读写IO的 tps TransactionsPerSecond的缩写,也就是事务数/秒 # tps:读写IO处理的一次响应事务 tps = str(t2_io.read_count + t2_io.write_count - t1_io.read_count - t1_io.write_count) + " tps"

网络信息


输出网络每个接口信息

psutil.net_io_counters(pernic=True)     #pernic=True

查看网卡

psutil.net_if_addrs().keys()
for i in psutil.net_if_addrs().keys():
    network = networkapi[i]
    print("网卡IP地址:", network[0][1])
    print("子网地址:", network[0][2])
    print("网卡MAC地址:", network[1][1])

示例:

# 获取网络信息
ionetwork = psutil.net_io_counters()# 发送总字节数
iobytes_sent = ionetwork.bytes_sent

# 接收总字节数
iobytes_recv = ionetwork.bytes_recv

# 发送总包个数
netpackets_sent = ionetwork.packets_sent

# 接收总包个数
netpackets_recv = ionetwork.packets_recv

# 接收错误数
errin = ionetwork.errin

# 发送错误数
errout = ionetwork.errout

# 求其传入数据包数量
dropin = ionetwork.dropin

# 丢弃传输数据包数量
dropout = ionetwork.dropout# 求出每秒的网络信息
t1_net = psutil.net_io_counters()
time.sleep(1)
t2_net = psutil.net_io_counters()# 求出每秒发送网卡流量
bytes_sent = t2_net.bytes_sent - t1_net.bytes_sent
bytes_sent = str(int(bytes_sent)/1024) + " KB"
print(bytes_sent)

# 求出每秒接收网卡流量
bytes_recv = t2_net.bytes_recv - t1_net.bytes_recv
bytes_recv = str(int(bytes_recv)/1024) + " KB"
print(bytes_recv)

# 求出每秒发送包的数量
packets_sent = t2_net.packets_sent - t1_net.packets_sent
print(packets_sent)

# 求出每秒接收报的数量
packets_recv = t2_net.packets_recv - t1_net.packets_recv
print(packets_recv)

系统信息


获取当前系统用户登录信息

psutil.users()
# 获取当前用户信息
user = psutil.users()
for i in user:
    if i.terminal == a:

        # 获取用户名
        username = i.name
        print("用户名:", username)

        # 虚拟终端
        terminal = i.terminal
        print("虚拟终端:", terminal)

        # 连接地址
        host = i.host
        print("连接地址:", host)

        # 以使用时间
        started = i.started
        print("使用时间:", started)

        # 用户pid
        userpid = i.pid    

获取开机时间

# 以linux时间格式返回
psutil.boot_time() 
# 转换成自然时间格式
datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S") 

进程信息


系统进程管理

获取当前系统的进程信息,获取当前程序的运行状态,包括进程的启动时间,查看设置CPU亲和度,内存使用率,IO信息
socket连接,线程数等
获取进程信息

查看系统全部进程

psutil.pids()

查看单个进程

p = psutil.Process(2423) 
p.name()                         #进程名
p.exe()                          #进程的bin路径
p.cwd()                          #进程的工作目录绝对路径
p.status()                       #进程状态
p.create_time()                  #进程创建时间
p.uids()                         #进程uid信息
p.gids()                         #进程的gid信息
p.cpu_times()                    #进程的cpu时间信息,包括user,system两个cpu信息
p.cpu_affinity()                 #get进程cpu亲和度,如果要设置cpu亲和度,将cpu号作为参考就好
p.memory_percent()               #进程内存利用率
p.memory_info()                  #进程内存rss,vms信息
p.io_counters()                  #进程的IO信息,包括读写IO数字及参数
p.connectios()                   #返回进程列表
p.num_threads()                  #进程开启的线程数
p.cpu_percent(interval=1)     #查看多少秒的进程cpu占用 interval后面跟秒

# 听过psutil的Popen方法启动应用程序,可以跟踪程序的相关信息 from subprocess import PIPE p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"],stdout=PIPE) p.name() p.username()

 

posted @ 2019-06-20 16:42  kevin.Xiang  阅读(3035)  评论(0编辑  收藏  举报