Psutil

来自linux中国网wiki
Evan讨论 | 贡献2021年7月18日 (日) 08:56的版本 →‎dva例子
跳到导航 跳到搜索


* usage

** cpu

 import psutil                                                                                                                                                        

In [3]: psutil.cpu_count()                                                                                                                                                   
Out[3]: 12

In [4]: psutil.cpu_count(logical=False)                                                                                                                                      
Out[4]: 6


统计CPU的用户/系统/空闲时间:


In [5]: psutil.cpu_times()                                                                                                                                                   
Out[5]: scputimes(user=7503.18, nice=16.75, system=2506.54, idle=383529.04, iowait=670.68, irq=0.0, softirq=471.62, steal=0.0, guest=0.0, guest_nice=0.0)


再实现类似top命令的CPU使用率,每秒刷新一次,累计10次:

>>> for x in range(10):
...     print(psutil.cpu_percent(interval=1, percpu=True))

** 内存

In [6]:  psutil.virtual_memory()                                                                                                                                             
Out[6]: svmem(total=16472592384, available=12100411392, percent=26.5, used=3397423104, free=8617963520, active=4693372928, inactive=1953992704, buffers=678100992, cached=3779104768, shared=629567488, slab=543322112)

'''
返回的是字节Byte为单位的整数
重点关注的参数是:
    1.total表示内存总的大小
    2.percent表示实际已经使用的内存占比。
    3.available表示还可以使用的内存。
    4.uused表示已经使用的内存
'''


🍒使用total获取内存总大小
>>> psutil.virtual_memory().total
2028425216

🍒使用获取已经使用的内存
>>> psutil.virtual_memory().used
865882112

🍧使用free获取剩余的内存
>>> psutil.virtual_memory().free
805871616


** 磁盘信息主要两部分,一个是磁盘的利用率,一个是io。获取磁盘相关

*** 3.1、psutil.disk_partitions()获取磁盘分区信息

   disk_partitions([all=False]):以命名元组的形式返回所有已挂载的磁盘,包含磁盘名称,挂载点,文件系统类型等信息。
   当all等于True时,返回包含/proc等特殊文件系统的挂载信息
   🥞获取磁盘分区的信息
   >>> psutil.disk_partitions()
   [sdiskpart(device='/dev/sda3', mountpoint='/', fstype='xfs', opts='rw,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota', maxfile=255, maxpath=4096), sdiskpart(device='/dev/loop1', mountpoint='/snap/core18/1944', fstype='squashfs', opts='ro,nodev,relatime', maxfile=256, maxpath=4096),。...sdiskpart(device='/dev/loop6', mountpoint='/snap/snap-store/467', fstype='squashfs', opts='ro,nodev,relatime', maxfile=256, maxpath=4096), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='xfs', opts='rw,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota', maxfile=255, maxpath=4096)]


   >>> io = psutil.disk_partitions()
   >>> print(io[-1])
   sdiskpart(device='/dev/sr0', mountpoint='/media/shawn/Ubuntu 20.04.1 LTS amd64', fstype='iso9660', opts='ro,nosuid,nodev,relatime,nojoliet,check=s,map=n,blocksize=2048,uid=1000,gid=1000,dmode=500,fmode=400', maxfile=255, maxpath=4096)
   >>> 


*** 3.2、psutil.disk_usage()获取路径所在磁盘的使用情况

   disk_usage(path):以命名元组的形式返回path所在磁盘的使用情况,包括磁盘的容量、已经使用的磁盘容量、磁盘的空间利用率等。

🍿获取根分区的使用情况 >>> psutil.disk_usage('/') sdiskusage(total=101184290816, used=8805330944, free=92378959872, percent=8.7) >>>

*** 3.3、disk_io_counters获取io统计信息

   disk_io_counters([perdisk]):以命名元组的形式返回磁盘io统计信息(汇总的),包括读、写的次数,读、写的字节数等。
   当perdisk的值为True,则分别列出单个磁盘的统计信息(字典:key为磁盘名称,value为统计的namedtuple)。

🍳获取磁盘总的io个数,读写信息 >>> psutil.disk_io_counters() sdiskio(read_count=60919, write_count=448417, read_bytes=1582292480, write_bytes=31438750208, read_time=50157, write_time=259374, read_merged_count=2527, write_merged_count=44226, busy_time=1096900)

补充说明 read_count(读IO数) write_count(写IO数) read_bytes(读IO字节数) write_bytes(写IO字节数) read_time(磁盘读时间) write_time(磁盘写时间)

🍚获取单个分区的IO和读写信息 >>> psutil.disk_io_counters(perdisk=True) {'loop0': sdiskio(read_count=43, write_count=0, read_bytes=358400, write_bytes=0, read_time=28, write_time=0, read_merged_count=0, write_merged_count=0, busy_time=44), 'loop1': sdiskio(read_count=424, write_count=0, read_bytes=6236160, write_bytes=0, read_time=277, write_time=0, read_merged_count=0, write_merged_count=0, busy_time=956),... write_merged_count=985, busy_time=1132488)}


** 获取网络信息

** sensors_传感器

psutil模块还未我们提供了可以查看获取计算机硬件、电池状态、硬件风扇速度等

>>> import psutil

🍝返回硬件的信息 >>> psutil.sensors_temperatures() {'acpitz': [shwtemp(label=, current=47.0, high=103.0, critical=103.0)],

'asus': [shwtemp(label=, current=47.0, high=None, critical=None)],
'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
             shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0)]}

>>>

🍟返回电池状态 >>> psutil.sensors_fans() {'asus': [sfan(label='cpu_fan', current=3200)]} >>>

🍘返回硬件风扇速度 >>> psutil.sensors_battery() sbattery(percent=93, secsleft=16628, power_plugged=False) >>>

🍋返回硬件温度 >>> psutil.sensors_temperatures(fahrenheit=False)



dva例子

In [2]: import psutil                                                                 

In [3]:  dic = psutil.net_if_addrs()                                                  

In [4]: dic                                                                           
Out[4]: 
{'lo': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None),
  snicaddr(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
  snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)],
 'wlan0': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.88.108', netmask='255.255.255.0', broadcast='192.168.88.255', ptp=None),
  snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fd67:f843:530::d8d', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
  snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fd67:f843:530:0:521e:82c5:9e16:3b2', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
  snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::d4c9:9f38:df07:bd12%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
  snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='60:f2:62:a8:3a:f9', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)],
 'eth0': [snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='34:48:ed:90:24:e3', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}

In [5]: def getIP(): 
   ...:     """获取ipv4地址""" 
   ...:     dic = psutil.net_if_addrs() 
   ...:     ipv4_list = [] 
   ...:     for adapter in dic: 
   ...:         snicList = dic[adapter] 
   ...:         for snic in snicList: 
   ...:             if snic.family.name == 'AF_INET': 
   ...:                 ipv4 = snic.address 
   ...:                 if ipv4 != '127.0.0.1': 
   ...:                     ipv4_list.append(ipv4) 
   ...:     if len(ipv4_list) >= 1: 
   ...:         return ipv4_list[0] 
   ...:     else: 
   ...:         return None 
   ...:                                                                               

In [6]: getIP()                                                                       
Out[6]: '192.168.88.108'


不错的解说过程 


def getIP():
    """获取ipv4地址"""
    dic = psutil.net_if_addrs()
    ipv4_list = []
    for adapter in dic:
        snicList = dic[adapter]
        for snic in snicList:
            if snic.family.name == 'AF_INET':
                ipv4 = snic.address
                if ipv4 != '127.0.0.1':
                    ipv4_list.append(ipv4)
    if len(ipv4_list) >= 1:
        return ipv4_list[0]
    else:
        return None

'''

In [14]: for adapter in dic: 
    ...:     snicList = dic[adapter] 
    ...:     print(snicList) 
    ...:     print('**************') 
    ...:     type(snicList) 
    ...:                                                            
[snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)]
**************
[snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.88.108', netmask='255.255.255.0', broadcast='192.168.88.255', ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fd67:f843:530::d8d', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fd67:f843:530:0:521e:82c5:9e16:3b2', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::d4c9:9f38:df07:bd12%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='60:f2:62:a8:3a:f9', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]
**************
[snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='34:48:ed:90:24:e3', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]
**************


In [15]: for adapter in dic: 
    ...:     snicList = dic[adapter] 
    ...:     for snic in snicList: 
    ...:         print('zzzzzz') 
    ...:         print(snic) 
    ...:          
    ...:                                                                                      
zzzzzz
snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.88.108', netmask='255.255.255.0', broadcast='192.168.88.255', ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fd67:f843:530::d8d', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fd67:f843:530:0:521e:82c5:9e16:3b2', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::d4c9:9f38:df07:bd12%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='60:f2:62:a8:3a:f9', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)
zzzzzz
snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='34:48:ed:90:24:e3', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)

In [16]: for adapter in dic: 
    ...:     snicList = dic[adapter] 
    ...:     for snic in snicList: 
    ...:         if snic.family.name == 'AF_INET': 
    ...:             ipv4 = snic.address 
    ...:             ipv4_list.append(ipv4) 
    ...:             print(ipv4_list) 
    ...:                                                                              
['127.0.0.1']
['127.0.0.1', '192.168.88.108']






'''






def getIP():
    """获取ipv4地址"""
    dic = psutil.net_if_addrs()
    ipv4_list = []
    for adapter in dic:
        snicList = dic[adapter]
        for snic in snicList:
            if snic.family.name == 'AF_INET':
                ipv4 = snic.address
                if ipv4 != '127.0.0.1':
                    ipv4_list.append(ipv4)
    if len(ipv4_list) >= 1:
        return ipv4_list[0]
    else:
        return None

查看系统硬件脚本

#!/usr/bin/python3
#coding:utf-8
##查看系统硬件脚本

import psutil
import datetime
import time

# 当前时间
now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
print(now_time)

# 查看cpu物理个数的信息
print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False))

#CPU的使用率
cpu = (str(psutil.cpu_percent(1))) + '%'
print(u"cup使用率: %s" % cpu)

#查看内存信息,剩余内存.free  总共.total
#round()函数方法为返回浮点数x的四舍五入值。

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(u"物理内存: %s G" % total)
print(u"剩余物理内存: %s G" % free)
print(u"物理内存使用率: %s %%" % int(memory * 100))
# 系统启动时间
print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))

# 系统用户
users_count = len(psutil.users())
#
# >>> for u in psutil.users():
# ...   print(u)
# ...
# suser(name='root', terminal='pts/0', host='61.135.18.162', started=1505483904.0)
# suser(name='root', terminal='pts/5', host='61.135.18.162', started=1505469056.0)
# >>> u.name
# 'root'
# >>> u.terminal
# 'pts/5'
# >>> u.host
# '61.135.18.162'
# >>> u.started
# 1505469056.0
# >>>

users_list = ",".join([u.name for u in psutil.users()])
print(u"当前有%s个用户,分别是 %s" % (users_count, users_list))

#网卡,可以得到网卡属性,连接数,当前流量等信息
net = psutil.net_io_counters()
bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
print(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent))

io = psutil.disk_partitions()
# print(io)
# print("io[-1]为",io[-1])
#del io[-1]

print('-----------------------------磁盘信息---------------------------------------')

print("系统磁盘信息:" + str(io))

for i in io:
    o = psutil.disk_usage(i.device)
    print("总容量:" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
    print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
    print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")

print('-----------------------------进程信息-------------------------------------')
# 查看系统全部进程
for pnum in psutil.pids():
    p = psutil.Process(pnum)
    print(u"进程名 %-20s  内存利用率 %-18s 进程状态 %-10s 创建时间 %-10s " \
    % (p.name(), p.memory_percent(), p.status(), p.create_time()))




evan@myxps:~/tmp$ python3  ps.py 
2021-07-18-15:00:08
物理CPU个数: 6
cup使用率: 2.8%
物理内存: 15.34 G
剩余物理内存: 9.19 G
物理内存使用率: 40 %
系统启动时间: 2021-07-18 11:35:59
当前有1个用户,分别是 evan
网卡接收流量 48.04 Mb 网卡发送流量 971.19 Mb
-----------------------------磁盘信息---------------------------------------
系统磁盘信息:[sdiskpart(device='/dev/nvme0n1p8', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro', maxfile=255, maxpath=4096), sdiskpart(device='/dev/nvme0n1p9', mountpoint='/home/evan/data', fstype='ext4', opts='rw,relatime', maxfile=255, maxpath=4096), sdiskpart(device='/dev/nvme0n1p1', mountpoint='/boot/efi', fstype='vfat', opts='rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro', maxfile=1530, maxpath=4096)]
总容量:7G
已用容量:0G
可用容量:7G
总容量:7G
已用容量:0G
可用容量:7G
总容量:7G
已用容量:0G
可用容量:7G
-----------------------------进程信息-------------------------------------
进程名 systemd               内存利用率 0.06825592315949582 进程状态 sleeping   创建时间 1626579359.07 
进程名 kthreadd              内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 rcu_gp                内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 rcu_par_gp            内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 kworker/0:0H-kblockd  内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 mm_percpu_wq          内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 ksoftirqd/0           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 rcu_sched             内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 migration/0           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 cpuhp/0               内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 cpuhp/1               内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 migration/1           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 ksoftirqd/1           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 kworker/1:0H-events_highpri  内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 cpuhp/2               内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 migration/2           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 ksoftirqd/2           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 kworker/2:0H-kblockd  内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 cpuhp/3               内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 migration/3           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 ksoftirqd/3           内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 
进程名 kworker/3:0H-events_highpri  内存利用率 0.0                进程状态 idle       创建时间 1626579359.07 
进程名 cpuhp/4               内存利用率 0.0                进程状态 sleeping   创建时间 1626579359.07 



* see also

psutil

python模块之psutil详解

[https://blog.csdn.net/weixin_44621343/article/details/112726406 Python运维自动化psutil 模块详解(超级详细) ]