參考官方文檔:
一、psutil簡介
psutil是一個開源且跨平台(
在Python中獲取系統信息的另一個好辦法是使用psutil
這個第三方模塊。還可以跨平台使用,支持Linux/UNIX/OSX/Windows等,是系統管理員和運維小伙伴不可或缺的必備模塊。
Works with Python versions from 2.4 to 3.X.
二、安裝psutil模塊
👀CentOS安裝psutil包:
🤖python版本:5.8
wget https://pypi.python.org/packages/source/p/psutil/psutil-5.8.0.tar.gz
tar zxvf psutil-5.8.0.tar.gz
cd psutil-5.8.0
yum -y install python-devel (如果提示缺少python.h頭文件,執行此命令。)
python setup.py install
😜Windos安裝psutil包:
root@shawn:~# pip3 install psutil
Collecting psutil
Downloading psutil-5.8.0-cp38-cp38-manylinux2010_x86_64.whl (296 kB)
|████████████████████████████████| 296 kB 20 kB/s
Installing collected packages: psutil
Successfully installed psutil-5.8.0
三、使用psutil模塊
1.獲取CPU信息:
1.1使用psutil.cpu_times()
方法
-
使用
psutil.cpu_times()
獲取CPU的完整信息
>>> import psutil
>>> psutil.cpu_times()
scputimes(user=733.23, nice=2.62, system=122.87, idle=19414.35, iowait=29.46, irq=0.0, softirq=34.18, steal=0.0, guest=0.0, guest_nice=0.0)
-
獲取單個數據,如用戶的cpu時或io等待時間。
>>> psutil.cpu_times().user
793.19
>>> psutil.cpu_times().iowait
31.79
1.2psutil.cpu_count()
獲取CPU個數
-
使用
psutil.cpu_count()
獲取CPU邏輯個數
#cpu_count(,[logical]):默認返回邏輯CPU的個數,當設置logical的參數為False時,返回物理CPU的個數。
>>> psutil.cpu_count()
8
使用psutil.cpu_count(logical=False)
獲取CPU的物理個數,默認logical值為True
>>> psutil.cpu_count(logical=False)
8
1.3psutil.getloadavg()
獲取平均系統負載
-
使用
psutil.getloadavg()
可以獲取平均系統負載,會以元組的形式返回最近1、5和15分鍾內的平均系統負載。
🍤 在Windows上,這是通過使用Windows API模擬的,該API產生一個線程,該線程保持在后台運行,並每5秒更新一次結果,從而模仿UNIX行為。 因此,在Windows上,第一次調用此方法,在接下來的5秒鍾內,它將返回無意義的(0.0,0.0,0.0)元組。
>>> psutil.getloadavg()
(1.22, 1.41, 1.38)
1.4、psutil.cpu_percent()
獲取CPU使用率
-
cpu_percent(,[percpu],[interval])
:返回CPU的利用率-
interval
:指定的是計算cpu使用率的時間間隔,interval不為0時,則阻塞時顯示interval執行的時間內的平均利用率 -
percpu
:指定是選擇總的使用率或者每個cpu的使用率,percpu
為True
時顯示所有物理核心的利用率
-
😍1.指定的是計算cpu使用率的時間間隔
>>> for x in range(10):
... psutil.cpu_percent(interval=1)
...
2.4
2.5
2.7
2.3
2.5
2.2
2.0
2.2
2.4
2.2
🎶2.實現類似top命令的CPU使用率,每秒刷新一次,累計10次:
>>> for x in range(10):
... psutil.cpu_percent(interval=1,percpu=True)
...
[1.0, 3.1, 5.0, 4.0, 0.0, 4.0, 3.0, 2.0]
...
[1.0, 1.0, 6.1, 3.1, 2.0, 2.1, 0.0, 0.0]
[2.0, 1.0, 6.0, 4.9, 1.0, 5.1, 1.0, 1.0]
1.5psutil.cpu_stats()
獲取CPU的統計信息
-
cpu_stats()以命名元組的形式返回CPU的統計信息,包括上下文切換,中斷,軟中斷和系統調用次數。
>>> psutil.cpu_stats()
scpustats(ctx_switches=3928927, interrupts=2319133, soft_interrupts=1974116, syscalls=0)
1.6、psutil.cpu_freq()
獲取CPU頻率
-
cpu_freq([percpu]):返回cpu頻率
>>> psutil.cpu_freq()
scpufreq(current=1799.999, min=0.0, max=0.0)
1.7、psutil.cpu_times_percent()
獲取耗時比例
-
cpu_times_percent(,[percpu]):功能和cpu_times大致相同,看字面意思就能知道,該函數返回的是耗時比例。
>>> psutil.cpu_times_percent()
scputimes(user=0.1, nice=0.0, system=0.0, idle=99.9, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
2.獲取內存信息
2.1psutil.virtual_memory()
內存使用情況
-
psutil.virtual_memory()
:獲取系統內存的使用情況,以命名元組的形式返回內存使用情況,包括總內存,可用內存,內存利用率,buffer和cache等。單位為字節。
🍒獲取內存的完整信息
>>> psutil.virtual_memory()
svmem(total=2028425216, available=982532096, percent=51.6, used=861827072, free=810414080, active=401735680, inactive=431902720, buffers=4096, cached=356179968, shared=9203712, slab=236351488)
'''
返回的是字節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
2.2 psutil.swap_memory()
獲取系統交換內存(swap)的統計信息
-
psutil.swap_memory()
:獲取系統交換內存的統計信息,以命名元組的形式返回swap/memory
使用情況,包含swap中頁的換入和換出。
🍖獲取交換分區相關
>>> psutil.swap_memory()
sswap(total=4091539456, used=173793280, free=3917746176, percent=4.2, sin=23683072, sout=188874752)
3.獲取磁盤相關
磁盤信息主要兩部分,一個是磁盤的利用率,一個是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)}
4.獲取網絡信息
4.1、psutil.net_io_counter([pernic])
獲取網卡io統計信息
-
psutil.net_io_counter([pernic]):以命名元組的形式返回當前系統中每塊網卡的網絡io統計信息,包括收發字節數,收發包的數量、出錯的情況和刪包情況。當pernic為True時,則列出所有網卡的統計信息。
🥘 獲取網絡讀寫字節/包的個數
>>> psutil.net_io_counters()
snetio(bytes_sent=242309, bytes_recv=6775236, packets_sent=2563, packets_recv=44703, errin=0, errout=0, dropin=9301, dropout=0)
🍨列出所有網卡的統計信息
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=38379, bytes_recv=38379, packets_sent=413, packets_recv=413, errin=0, errout=0, dropin=0, dropout=0), 'ens32': snetio(bytes_sent=203930, bytes_recv=6756079, packets_sent=2150, packets_recv=44430, errin=0, errout=0, dropin=9334, dropout=0)}
4.2、psutil.net_if_addrs()
獲取網絡接口信息
-
psutil.net_if_addrs():以字典的形式返回網卡的配置信息,包括IP地址和mac地址、子網掩碼和廣播地址。
>>> psutil.net_if_addrs()
{'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)], 'ens32': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.12.154', netmask='255.255.255.0', broadcast='192.168.12.255', ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::1c00:63d1:f5bf:1cec%ens32', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_PACKET: 17>, address='00:0c:29:7a:81:66', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
4.3、psutil.net_if_stats()獲取網絡接口狀態信息
-
psutil.net_if_stats():返回網卡的詳細信息,包括是否啟動、通信類型、傳輸速度與mtu。
>>> psutil.net_if_stats()
{'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536), 'ens32': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1000, mtu=1500)}
4、4、psutil.net_connections():獲取當前網絡連接信息
-
psutil.net_connections():以列表的形式返回,獲取當前網絡連接信息
>>> psutil.net_connections()
Traceback (most recent call last):
...
PermissionError: [Errno 1] Operation not permitted
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
psutil.AccessDenied: psutil.AccessDenied (pid=3847)
🥓你可能會得到一個AccessDenied錯誤,原因是psutil獲取信息也是要走系統接口,而獲取網絡連接信息需要root權限,這種情況下,可以退出Python交互環境,用sudo重新啟動:
$ sudo python3
Password: ******
Python 3.6.3 ... on darwin
Type "help", ... for more information.
>>> import psutil
>>> psutil.net_connections()
[
sconn(fd=83, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::127.0.0.1', port=62911), raddr=addr(ip='::127.0.0.1', port=3306), status='ESTABLISHED', pid=3725),
sconn(fd=84, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::127.0.0.1', port=62905), raddr=addr(ip='::127.0.0.1', port=3306), status='ESTABLISHED', pid=3725),
sconn(fd=93, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::', port=8080), raddr=(), status='LISTEN', pid=3725),
sconn(fd=103, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::127.0.0.1', port=62918), raddr=addr(ip='::127.0.0.1', port=3306), status='ESTABLISHED', pid=3725),
sconn(fd=105, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725),
sconn(fd=106, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725),
sconn(fd=107, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725),
...
sconn(fd=27, family=<AddressFamily.AF_INET: 2>, type=2, ..., pid=1)
]
4.5psutil.net_connections()
網絡連接的詳細信息
-
psutil.net_connections([kind]):以列表的形式返回每個網絡連接的詳細信息(namedtuple)。命名元組包含fd, family, type, laddr, raddr, status, pid等信息。kind表示過濾的連接類型,支持的值如下:(默認為inet)
🍪inet 代表 IPv4 and IPv6
>>> psutil.net_connections(kind='inet')
[sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, laddr=addr(ip='192.168.12.154', port=58478)...sconn(fd=-1, family=<AddressFamily.AF_INET6: 10>, type=<SocketKind.SOCK_STREAM: 1>, laddr=addr(ip='::1', port=631), raddr=(), status='LISTEN', pid=None)]
>>>
5.獲取其他系統信息
5.1獲取開機時間
🍹以linux時間格式返回,可以使用時間戳轉換
>>> import psutil
>>> psutil.boot_time()
1610705729.0
🍨轉換成自然時間格式
>>> import psutil
>>> psutil.boot_time()
1610705729.0
>>> import datetime
>>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H: %M: %S")
'2021-01-15 18: 15: 29'
5.2獲取連接系統的用戶列表
使用psutil.users()
可以獲取當前連接的系統用戶列表
>>> import psutil
>>> psutil.users()
[suser(name='shawn', terminal=':0', host='localhost', started=1610705792.0, pid=1442)]
>>> for u in psutil.users():
... print(u)
...
suser(name='shawn', terminal=':0', host='localhost', started=1610705792.0, pid=1442)
>>> u.name
'shawn'
>>> u.terminal
':0'
>>> u.host
'localhost'
>>> u.started
1610705792.0
>>>
6.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)
7.獲取查看進程
7.1psutil.pids
獲取系統全部進程
🥩以列表的形式返回當前正在運行的進程
>>> psutil.pids()
[1, 2, 3, 4, 6, 9, 10, 11, 12, 13, 14,
...
3929, 3930, 3949, 3955, 3975, 3989, 4564, 4619, 4625, 4626]
7.2psutil.Process()
方法查看系統單個進程
-
psutil.Process( pid ):對進程進行封裝,可以使用該類的方法獲取進行的詳細信息,或者給進程發送信號。傳入參數為pid
-
psutil.Process( pid )獲取進程相關信息的方法如下:
>>> p = psutil.Process(8216) #獲取當前指定進程ID
>>> p.name() #進程名
'bash'
>>> p.exe() #進程的bin路徑
'/usr/bin/bash'
>>> p.cwd() #進程的工作目錄絕對路徑
'/root'
>>> p.cmdline() # 進程啟動的命令行
['bash']
>>> p.ppid() # 父進程ID
8215
>>> p.parent() # 父進程
psutil.Process(pid=8215, name='su', status='sleeping', started='22:59:40')
>>> p.children() # 子進程列表
[psutil.Process(pid=8224, name='python3', status='running', started='22:59:56')]
>>> p.num_threads() #進程的子進程個數
1
>>> p.status() #進程狀態
'sleeping'
>>> p.create_time() #進程創建時間
1610722781.1
>>> p.uids() #進程uid信息
puids(real=0, effective=0, saved=0)
>>> p.gids() #進程的gid信息
pgids(real=0, effective=0, saved=0)
>>> p.cpu_times() #進程使用cpu時間信息,包括user,system兩個cpu信息
pcputimes(user=0.0, system=0.01, children_user=0.01, children_system=0.0, iowait=0.0)
>>> p.cpu_affinity() #get進程cpu親和度,如果要設置cpu親和度,將cpu號作為參考就好
[0, 1, 2, 3, 4, 5, 6, 7]
>>> p.memory_percent() #進程內存利用率
0.19627600606597861
>>> p.memory_info() #進程使用的內存rss,vms信息
pmem(rss=3981312, vms=13230080, shared=3432448, text=724992, lib=0, data=712704, dirty=0)
>>> p.io_counters() #進程的IO信息,包括讀寫IO數字及參數
pio(read_count=140, write_count=28, read_bytes=180224, write_bytes=0, read_chars=66146, write_chars=1759)
>>> p.connections() # 進程相關網絡連接
[]
>>> p.num_threads()