psutil 模塊
參考官方檔案:https://pypi.org/project/psutil/
一、psutil簡介
psutil是一個開源且跨平臺(http://code.google.com/p/psutil/)的庫,能夠輕松實作**獲取系統運行的行程和系統利用率(包括CPU、記憶體、磁盤、網路等)資訊,它主要應用于系統監控,分析和限制系統資源及行程的管理,它實作了同等命令列工具提供的功能,**如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等,
在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() #行程開啟的執行緒數
1
>>> p.threads() # 所有執行緒資訊
[pthread(id=8216, user_time=0.0, system_time=0.01)]
>>> p.terminal() # 行程終端
'/dev/pts/1'
>>> p.open_files() # 行程打開的檔案
[]
>>> p.environ() # 行程環境變數
{'SHELL': '/bin/bash', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...', 'PWD': '/Users/michael', 'LANG': 'zh_CN.UTF-8', ...}
>>> p.terminate() # 發送SIGTEAM信號結束行程
Terminated: 15
>>> p.kill() #發送SIGKILL信號結束行程
>>> 已殺死
>>> p.is_running() #行程是否在運行
True
>>> p.num_fds() #行程打開的檔案個數
4
>>> p.is_running() #判斷行程是否正在運行
True
popen方法的使用:獲取(跟蹤)用戶啟動的應用程式行程資訊
>>> import psutil
>>> from subprocess import PIPE
>>> p = psutil.Popen(["/usr/bin/python3", "-c", "print('hello')"],stdout=PIPE)
>>> p.name()
'python3'
>>> p.username()
'shawn'
>>> p.communicate()
(b'hello\n', None)
>>> p.wait(timeout=2)
0
7.其他行程相關的操作
🥖1.psutil.pid_exists判斷給點定的pid是否存在
>>> psutil.pid_exists(1)
True
🍛2.psutil.process_iter迭代當前正在運行的行程,回傳的是每個行程的Process物件
>>> psutil.process_iter(8216)
<generator object process_iter at 0x7f48a7275040>
8.psutil模塊的其他補充:
psutil還提供了一個test()方法,可以模擬出ps命令的效果:
>>> import psutil
>>> psutil.test()
USER PID %MEM VSZ RSS NICE STATUS START TIME CMDLINE
root 1 0.6 164.9M 11.4M sleep 18:15 01:01 /sbin/init s
root 2 0.0 0.0B 0.0B sleep 18:15 00:00 kthreadd
...
root 7896 0.0 0.0B 0.0B idle 21:55 00:00 kworker/u256
shawn 7904 1.5 49.2M 29.1M runni 21:58 00:00 python3
>>>
Windows services:獲取windows的服務
>>> list(psutil.win_service_iter())
[<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
<WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
<WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
<WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
...]
>>> psutil.win_service_get('alg')
<WindowsService(name='alg', display_name='Application Layer Gateway Service') at 2325310212128>
>>> s = psutil.win_service_get('alg')
>>> s.as_dict()
{'binpath': 'C:\\Windows\\System32\\alg.exe',
'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
'display_name': 'Application Layer Gateway Service',
'name': 'alg',
'pid': None,
'start_type': 'manual',
'status': 'stopped',
'username': 'NT AUTHORITY\\LocalService'}
四、撰寫獲取系統硬體腳本
'''
Author:淘小欣
blog:https://blog.taoxiaoxin.club/
script_info:檢測系統硬體腳本
Edition:v0.0.1
'''
# !/usr/bin/env python
# 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("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("物理記憶體: %s G" % total)
print("剩余物理記憶體: %s G" % free)
print("物理記憶體使用率: %s %%" % int(memory * 100))
# 獲取系統啟動時間
print("系統啟動時間: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))
# 獲取系統用戶
users_count = len(psutil.users())
users_list = ",".join([u.name for u in psutil.users()])
print("當前有%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("網卡接收資料 %s 網卡發送資料 %s" % (bytes_rcvd, bytes_sent))
# 獲取磁盤資料資訊
io = psutil.disk_partitions()
print('-----------------------------磁盤資訊---------------------------------------')
for i in io:
try:
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")
except PermissionError:
continue
print('-----------------------------行程資訊-------------------------------------')
# 查看系統全部行程
for pnum in psutil.pids():
p = psutil.Process(pnum)
print(
"行程名 %-20s 記憶體利用率 %-18s 行程狀態 %-10s 創建時間 %-10s " % (p.name(), p.memory_percent(), p.status(), p.create_time()))
五、參考資料
- https://www.liaoxuefeng.com/wiki/1016959663602400/1183565811281984
- https://pypi.org/project/psutil/
- https://www.cnblogs.com/billie52707/p/12468740.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/249840.html
標籤:其他
上一篇:成為進階Linux大佬的第一步
下一篇:shell基礎教程
