主頁 >  其他 > Python運維自動化psutil 模塊詳解(超級詳細)

Python運維自動化psutil 模塊詳解(超級詳細)

2021-01-17 12:22:51 其他

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.00.00.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的使用率,percpuTrue時顯示所有物理核心的利用率

😍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基礎教程

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more