1.模塊簡介
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等。目前支持32位和64位的Linux、 Windows、OS X、FreeBSD和Sun Solaris等操作系統,支持從2.4到3.4的Python版本。
通常我們獲取操作系統信息往往采用編寫shell來實現,如獲取當前物理內存總大小及已使用大小,shell命令如下:
[root@prometheus01 ~]# free -b|grep Mem|awk '{print $2}'
4125114368
[root@prometheus01 ~]# free -b|grep Mem|awk '{print $3}'
146026496
相比較而言,使用psutil庫實現則更加簡單明了。psutil大小單位一般都采用字節,如下:
[root@prometheus01 ~]# python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import psutil
>>> mem=psutil.virtual_memory()
>>> mem.total,mem.used
(4125114368, 200011776)
2.獲取系統性能信息
采集系統的基本性能信息包括CPU、內存、磁盤、網絡等,可以完整描述當前系統的運行狀態及質量。psutil模塊已經封裝了這些方法,用戶可以根據自身的應用場景,調用相應的方法來滿足需求,非常簡單實用。
2.1CPU信息Linux操作系統的CPU利用率有以下幾個部分
User Time,執行用戶進程的時間百分比
System Time,執行內核進程和中斷的時間百分比
Wait IO,由於IO等待而使CPU處於idle(空閑)狀態的時間百分比;
Idle,CPU處於idle狀態的時間百分比。
我們使用Python的psutil.cpu_times()方法可以非常簡單地得到這些信息,同時也可以獲取CPU的硬件相關信息,比如CPU的物理個數與邏輯個數,具體見下面的操作例子
- 獲取全部cpu信息
>>> psutil.cpu_times()
scputimes(user=966.81, nice=4.77, system=3096.13, idle=5485146.9, iowait=79.52, irq=0.0, softirq=132.47, steal=0.0, guest=0.0, guest_nice=0.0)
- 獲取cpu某個指標的cpu信息
# cpu用戶時間百分比
>>> psutil.cpu_times().user
966.83
# 邏輯cpu數量
>>> psutil.cpu_count()
2
# 物理cpu的數量
>>> psutil.cpu_count(logical=False)
1
2.2內存信息
Linux系統的內存利用率信息涉及total(內存總數)、used(已使 用的內存數)、free(空閑內存數)、buffers(緩沖使用數)、 cache(緩存使用數)、swap(交換分區使用數)等,分別使用 psutil.virtual_memory()與psutil.swap_memory()方法獲取這些信 息,具體見下面的操作例子:
獲取全部內存信息:
>>> mem=psutil.virtual_memory()
>>> mem
svmem(total=4125114368, available=3599085568, percent=12.8, used=201023488, free=210567168, active=1976868864, inactive=1640312832, buffers=3289088, cached=3710234624, shared=37261312, slab=203649024)
獲取內存某個指標信息:
# 總內存
>>> mem.total
4125114368
# 空閑內存
>>> mem.free
210567168
# swap分區信息
>>> psutil.swap_memory()
sswap(total=2147479552, used=270336, free=2147209216, percent=0.0, sin=0, sout=28672)
2.3磁盤信息
在系統的所有磁盤信息中,我們更加關注磁盤的利用率及IO信 息,其中磁盤利用率使用psutil.disk_usage方法獲取。磁盤IO信息包括 read_count(讀IO數)、write_count(寫IO數)、read_bytes(IO讀字節 數)、write_bytes(IO寫字節數)、read_time(磁盤讀時間)、 write_time(磁盤寫時間)等。這些IO信息可以使用 psutil.disk_io_counters()獲取,具體見下面的操作例子:
# 獲取磁盤的掛載信息
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/mapper/centos-root', mountpoint='/', fstype='xfs', opts='rw,relatime,attr2,inode64,noquota'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='xfs', opts='rw,relatime,attr2,inode64,noquota')]
# 獲取根目錄的磁盤使用情況
>>> psutil.disk_usage('/')
sdiskusage(total=104961515520, used=4649857024, free=100311658496, percent=4.4)
# 獲取磁盤整體io的信息
>>> psutil.disk_io_counters()
sdiskio(read_count=15805, write_count=330268, read_bytes=513860096, write_bytes=11843909632, read_time=10913, write_time=357121, read_merged_count=12, write_merged_count=14355, busy_time=141680)
# 更細粒度的獲取每塊盤的磁盤io信息
>>> psutil.disk_io_counters(perdisk=True)
{'sda': sdiskio(read_count=8896, write_count=159022, read_bytes=260540416, write_bytes=5923184128, read_time=5603, write_time=165861, read_merged_count=12, write_merged_count=14356, busy_time=71005), 'sda1': sdiskio(read_count=1868, write_count=2121, read_bytes=6856192, write_bytes=2342912, read_time=323, write_time=205, read_merged_count=0, write_merged_count=0, busy_time=513), 'sda2': sdiskio(read_count=6998, write_count=156901, read_bytes=252611072, write_bytes=5920841216, read_time=5272, write_time=165656, read_merged_count=12, write_merged_count=14356, busy_time=70500), 'sr0': sdiskio(read_count=36, write_count=0, read_bytes=2105344, write_bytes=0, read_time=61, write_time=0, read_merged_count=0, write_merged_count=0, busy_time=46), 'dm-0': sdiskio(read_count=6740, write_count=171250, read_bytes=247876096, write_bytes=5920812544, read_time=5221, write_time=191152, read_merged_count=0, write_merged_count=0, busy_time=70562), 'dm-1': sdiskio(read_count=133, write_count=7, read_bytes=3338240, write_bytes=28672, read_time=28, write_time=117, read_merged_count=0, write_merged_count=0, busy_time=69)}
4.4網絡信息
系統的網絡信息與磁盤IO類似,涉及幾個關鍵點,包括 bytes_sent(發送字節數)、bytes_recv(接收字節數)、 packets_sent(發送數據包數)、packets_recv(接收數據包數)等。這些網絡信息使用psutil.net_io_counters()方法獲取,具體見下面的操作例子:
# 使用psutil.net_io_counters獲取網絡總IO信息,默認pernic為False
>>> psutil.net_io_counters()
snetio(bytes_sent=81534167, bytes_recv=1700214232, packets_sent=745802, packets_recv=1468433, errin=0, errout=0, dropin=0, dropout=0)
# pernic=True獲取每個網絡接口的網絡io信息
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=50811, bytes_recv=50811, packets_sent=616, packets_recv=616, errin=0, errout=0, dropin=0, dropout=0), 'ens33': snetio(bytes_sent=81489782, bytes_recv=1700167321, packets_sent=745217, packets_recv=1467861, errin=0, errout=0, dropin=0, dropout=0)}
4.5其他系統信息
除了前面介紹的幾個獲取系統基本信息的方法,psutil模塊還支持獲取用戶登錄,開機信息等信息,具體見下面的操作例子:
>>> psutil.users()
[suser(name='root', terminal='tty1', host='', started=1645193344.0, pid=660), suser(name='root', terminal='pts/0', host='192.168.172.1', started=1648517248.0, pid=95380), suser(name='root', terminal='pts/1', host='192.168.172.1', started=1648523520.0, pid=95596)]
>>> import psutil,datetime
# 系統開機時間,以時間戳的形式表示
>>> psutil.boot_time()
1645772186.0
# 格式化轉換為自然時間
>>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
'2022-02-25 14:56:26'
4.6系統進程管理方法
獲得當前系統的進程信息,可以讓運維人員得知應用程序的運行狀態,包括進程的啟動時間、查看或設置CPU親和度、內存使用率、IO信息、socket連接、線程數等,這些信息可以呈現出指定進程是否存活、資源利用情況,為開發人員的代碼優化、問題定位提供很好的數據參考。
1.進程信息 psutil模塊在獲取進程信息方面也提供了很好的支持,包括使用 psutil.pids()方法獲取所有進程PID,使用psutil.Process()方法獲取單個進程的名稱、路徑、狀態、系統資源利用率等信息,具體見下面的操作例子:
>>> import psutil
# 列出所有進程PID
>>> psutil.pids()
[1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 33, 34, 35, 36, 44, 46, 47, 48, 50, 63, 97, 274, 275, 276, 284, 285, 286, 287, 288, 289, 290, 291, 368, 369, 378, 379, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 473, 494, 497, 520, 585, 586, 588, 590, 591, 594, 595, 597, 614, 637, 638, 641, 642, 648, 649, 660, 821, 891, 892, 893, 894, 1017, 1027, 1156, 12247, 20492, 24907, 30475, 33111, 90329, 94520, 94729, 95378, 95380, 95552, 95559, 95596, 95630, 95702, 95708, 95709, 95728]
# 實例化一個Process對象,參數為一進程PID
>>> p=psutil.Process(95378)
# 進程名
>>> p.name()
'sshd'
# 進程執行路徑
>>> p.exe()
'/usr/sbin/sshd'
# 進程工作目錄絕對路徑
>>> p.cwd()
'/'
# 進程狀態
>>> p.status()
'sleeping'
# 進程創建時間,時間戳格式
>>> p.create_time()
1648517277.12
# 進程uid信息
>>> p.uids()
puids(real=0, effective=0, saved=0)
# 進程gid信息
>>> p.gids()
pgids(real=0, effective=0, saved=0)
# 進程CPU時間信息,包括user,system兩個cpu時間
>>> p.cpu_times()
pcputimes(user=0.04, system=0.64, children_user=0.0, children_system=0.0, iowait=0.0)
# 進程內存利用率
>>> p.memory_percent()
0.1517215631292771
# 進程IO信息,包括讀寫IO數及字節數
>>> p.io_counters()
pio(read_count=3960, write_count=3544, read_bytes=1032192, write_bytes=0, read_chars=960672, write_chars=358255)
# 返回打開進程socket的namedutples列表,包括fs,family,laddr
>>> p.connections()
[pconn(fd=3, family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, laddr=addr(ip='192.168.172.41', port=22), raddr=addr(ip='192.168.172.1', port=62362), status='ESTABLISHED')]
# 進程開啟的線程數
>>> p.num_threads()
1
psutil提供的popen類的作用是獲取用戶啟動的應用程序進程信息,以便跟蹤程序進程的運行狀態。具體實現方法如下:
>>> import psutil
>>> from subprocess import PIPE
>>> p=psutil.Popen(["/usr/bin/python","-c" "print('hello')"],stdout=PIPE)
>>> p.name()
'python3'
>>> p.username()
'root'
>>> p.communicate()
(b'hello\n', None)
# 得到進程運行的cpu時間
>>> p.cpu_times()
pcputimes(user=0.0, system=0.0, children_user=0.0, children_system=0.0, iowait=0.0)
3.關於psutil模塊更多用法
>>> dir(psutil)
['AF_LINK', 'AIX', 'AccessDenied', 'BSD', 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT', 'Error', 'FREEBSD', 'IOPRIO_CLASS_BE', 'IOPRIO_CLASS_IDLE', 'IOPRIO_CLASS_NONE', 'IOPRIO_CLASS_RT', 'LINUX', 'MACOS', 'NETBSD', 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', 'NoSuchProcess', 'OPENBSD', 'OSX', 'POSIX', 'POWER_TIME_UNKNOWN', 'POWER_TIME_UNLIMITED', 'PROCFS_PATH', 'PermissionError', 'Popen', 'Process', 'ProcessLookupError', 'RLIMIT_AS', 'RLIMIT_CORE', 'RLIMIT_CPU', 'RLIMIT_DATA', 'RLIMIT_FSIZE', 'RLIMIT_LOCKS', 'RLIMIT_MEMLOCK', 'RLIMIT_MSGQUEUE', 'RLIMIT_NICE', 'RLIMIT_NOFILE', 'RLIMIT_NPROC', 'RLIMIT_RSS', 'RLIMIT_RTPRIO', 'RLIMIT_RTTIME', 'RLIMIT_SIGPENDING', 'RLIMIT_STACK', 'RLIM_INFINITY', 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', 'STATUS_PARKED', 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKING', 'STATUS_ZOMBIE', 'SUNOS', 'TimeoutExpired', 'WINDOWS', 'ZombieProcess', '_LOWEST_PID', '_PY3', '_TOTAL_PHYMEM', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_as_dict_attrnames', '_assert_pid_not_reused', '_common', '_compat', '_cpu_busy_time', '_cpu_times_deltas', '_cpu_tot_time', '_last_cpu_times', '_last_cpu_times_2', '_last_per_cpu_times', '_last_per_cpu_times_2', '_lock', '_pmap', '_ppid_map', '_pprint_secs', '_pslinux', '_psplatform', '_psposix', '_psutil_linux', '_psutil_posix', '_timer', '_wrap_numbers', 'boot_time', 'collections', 'contextlib', 'cpu_count', 'cpu_freq', 'cpu_percent', 'cpu_stats', 'cpu_times', 'cpu_times_percent', 'datetime', 'disk_io_counters', 'disk_partitions', 'disk_usage', 'functools', 'getloadavg', 'long', 'net_connections', 'net_if_addrs', 'net_if_stats', 'net_io_counters', 'os', 'pid_exists', 'pids', 'process_iter', 'pwd', 'sensors_battery', 'sensors_fans', 'sensors_temperatures', 'signal', 'subprocess', 'swap_memory', 'sys', 'test', 'threading', 'time', 'users', 'version_info', 'virtual_memory', 'wait_procs']
psutil官網:https://psutil.readthedocs.io/en/latest/
psuti的git:https://github.com/giampaolo/psutil