本文共 6194 字,大约阅读时间需要 20 分钟。
psutil 是一个跨平台的库,能够轻松实现获取系统运行的进程和系统利用例(CPU,磁盘,内存,网络等)信息,主要运用于系统监控,分析系统资源和进程管理。psutil比在shell中使用一连串的命令(ps,top,lsof,df,who,ionice,iostat等)命令来分析系统要简单方便得多。
源码安装:
# yum install gcc python-devel -y# wget https://pypi.python.org/packages/source/p/psutil/psutil-3.2.2.tar.gz# tar zxvf psutil-3.2.2.tar.gz# cd psutil-3.2.2# python setup.py install
或者
# yum install gcc python-devel python-pip# pip install psutil
== 本文使用的是最新版:psutil-5.4.3 ==
psutil.cpu_times(percpu=False) 在特定模式下,将会返回CPU所花费的时间(单位为秒)。
iowait : 由于IO等待而使得CPU处于空闲状态下的时间
import psutil
psutil.cpu_times()scputimes(user=2602.17, nice=1.66, system=618.36, idle=427625.83, iowait=88.21, irq=0.0, softirq=3.2, steal=0.0, guest=0.0, guest_nice=0.0)
psutil.cpu_percent(interval=None, percpu=False) 将会以百分比的形式返回当前系统范围的CPU的利用率。
>>> import psutil>>> psutil.cpu_percent() 0.4
psutil.cpu_times_percent(interval = None,percpu = False )在特定模式下,将会返回CPU所花费的时间百分比。
>>> psutil.cpu_times_percent()scputimes(user=0.5, nice=0.0, system=0.1, idle=99.3, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
psutil.cpu_count(logical=True) 将会返回cpu的数量。
>>> psutil.cpu_count()1>>> psutil.cpu_count(logical=False)1
psutil.cpu_stats()将各种CPU统计的信息作为元组返回。
syscalls:自启动以来的系统调用次数(在linux上始终是0)
psutil.cpu_stats()
scpustats(ctx_switches=113630366, interrupts=43135192, soft_interrupts=16865060, syscalls=0)
psutil.virtual_memory()将返回内存的信息
shared:可能被多个进程同时访问的内存
import psutil
psutil.virtual_memory()svmem(total=1928933376, available=1579491328, percent=18.1, used=140374016, free=388231168, active=739442688, inactive=614158336, buffers=197230592, cached=1203097600, shared=17080320)
psutil.swap_memory() 显示系统交换分区内存状态
>>> psutil.swap_memory()sswap(total=0, used=0, free=0, percent=0.0, sin=0, sout=0)
psutil.disk_partitions(all=False) 显示磁盘的完整信息
>>> import psutil>>> psutil.disk_partitions()[sdiskpart(device='/dev/vda1', mountpoint='/', fstype='ext4', opts='rw,relatime,data=ordered')]
psutil.disk_usage(path) 显示指定路径下该分区的磁盘使用情况。
>>> psutil.disk_usage('/')sdiskusage(total=42139451392, used=2603651072, free=37371645952, percent=6.5)
psutil.disk_io_counters(perdisk = False,nowrap = True ) 显示磁盘IO状态
write_bytes:写入的字节数
psutil.disk_io_counters()
sdiskio(read_count=14417, write_count=240266, read_bytes=339760128, write_bytes=3756941312, read_time=18711, write_time=1868954, read_merged_count=6, write_merged_count=160429, busy_time=172636)
psutil.net_io_counters(pernic=False) 显示系统网络总的IO信息(pernic=True时输出每个网络接口的信息)
dropout:丢弃的传出数据包总数
>>> import psutil>>> psutil.net_io_counters()snetio(bytes_sent=255022940, bytes_recv=306418164, packets_sent=676193, packets_recv=917168, errin=0, errout=0, dropin=0, dropout=0)>>> psutil.net_io_counters(pernic = True){'lo': snetio(bytes_sent=20308543, bytes_recv=20308543, packets_sent=327488, packets_recv=327488, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=234931775, bytes_recv=286168192, packets_sent=349278, packets_recv=590368, errin=0, errout=0, dropin=0, dropout=0)}
psutil.net_if_addrs() 显示网卡信息
psutil.net_if_addrs()
{'lo': [snic(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snic(family=17, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)], 'eth0': [snic(family=2, address='172.16.252.8', netmask='255.255.255.0', broadcast='172.16.252.255', ptp=None), snic(family=17, address='00:16:3e:06:87:05', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
psutil.boot_time() 显示系统启动的时间(以时间戳的格式)
>>> psutil.boot_time()1521532676.0>>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")'2018-03-20 15:57:56'
psutil.users() 显示当前连接到系统的用户
>>> psutil.users()[suser(name='root', terminal='pts/0', host='123.151.91.3', started=1521980032.0, pid=1059), suser(name='root', terminal='pts/1', host='123.151.91.3', started=1521977600.0, pid=807), suser(name='root', terminal='pts/2', host='123.151.91.3', started=1521981440.0, pid=1231), suser(name='dianel', terminal='pts/3', host='123.151.91.3', started=1521981568.0, pid=1372)]
psutil.pids() 获取当前所有进程的PID列表
>>> psutil.pids()[1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 25, 26, 27, 28, 29, 37, 38, 39, 40, 41, 60, 92, 216, 235, 236, 237,...]
psutil.process_iter(attrs=None, ad_value=None) 迭代显示本机所有运行的进程的类实例。
>>> import psutil>>> for proc in psutil.process_iter():... try:... pinfo = proc.as_dict(attrs=['pid', 'name', 'username'])... except psutil.NoSuchProcess:... pass... else:... print(pinfo)... {'username': 'root', 'pid': 1, 'name': 'systemd'}{'username': 'root', 'pid': 2, 'name': 'kthreadd'}{'username': 'root', 'pid': 3, 'name': 'ksoftirqd/0'}{'username': 'root', 'pid': 5, 'name': 'kworker/0:0H'}{'username': 'root', 'pid': 6, 'name': 'kworker/u2:0'...
psutil.Process()获取单个进程的信息。
>>> p = psutil.Process(2201) #实例化一个进程PID>>> p.name() #进程名'sshd' >>> p.exe() #进程bin路径'/usr/sbin/sshd'>>> p.cwd() #经常工作目录'/' >>> p.status() #进程状态'sleeping'>>> p.create_time() #进程创建时间1521532688.63>>> p.uids() #进程uidpuids(real=0, effective=0, saved=0)>>> p.gids() #进程gidpgids(real=0, effective=0, saved=0)>>> p.cpu_times() #进程CPU时间信息pcputimes(user=0.0, system=0.03, children_user=1.58, children_system=0.91)>>> p.cpu_affinity()[0]>>> p.memory_percent() #进程内存利用率0.21213298763513128>>> p.io_counters() #进程IO信息pio(read_count=45338, write_count=24689, read_bytes=3084288, write_bytes=200704, read_chars=33964000, write_chars=9986191)
popen类:获取用户启动的应用程序进程信息,方便跟踪程序进程状态
>>> import psutil>>> from subprocess import PIPE>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)>>> p.name()'python'>>> p.username()'root'>>> p.username()'root'>>> p.communicate()('hello\n', None)>>> p.wait(timeout=2)0
ending...
转载于:https://blog.51cto.com/dianel/2090968