python 的psutil简介
一、psutil模块:1.psutil是一个跨平台库(http://pythonhosted.org/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.安装psutil模块:
?二、.获取系统基本信息的使用: 1.CPU信息使用cpu_times方法获取cpu的完整信息,如下所示。 >>>import psutil 获取单个数据,如用户的cpu时或io等待时间,如下所示: >>> psutil.cpu_times().user 650617.11 >>> psutil.cpu_times().iowait 68894.63 >>> ?获取cpu逻辑和物理个数,默认logical值为True 。 #CPU逻辑个数 >>> psutil.cpu_count() 2 #CPU物理个数 >>> psutil.cpu_count(logical=False) 1 >>> ? 获取cpu的使用率: >>> psutil.cpu_percent() 2.5 >>> psutil.cpu_percent(1) 2.5 >>> >>> psutil.cpu_percent(True,1)
import psutil
if __name__ == ‘__main__‘:
print(psutil.cpu_percent(percpu=True,interval=1))
2.内存信息 内存信息的获取主要使用virtual_memory方法。swap使用就用swap_memory方法。 >>> mem = psutil.virtual_memory() >>> mem svmem(total=4018601984,available=1066205184,percent=73.5,used=3904004096,free=114597888,active=3302174720,inactive=426078208,buffers=156520448,cached=795086848) >>> mem.total 4018601984 >>> mem.used 3904004096 >>> mem.free 114597888#默认单位字节 >>> print(mem.total/1024/1024) 3832.4375 >>> 其中percent表示实际已经使用的内存占比,即(1047543808-717537280)/1047543808*100% 。available表示还可以使用的内存。 ?3.磁盘信息 磁盘信息主要有两部分,一个是磁盘的利用率,一个是io,他们分别可以通过disk_usage和disk_io_counters方法获取。 如下先获取分区信息,然后看下根分区的使用情况: >>> psutil.disk_partitions() [sdiskpart(device=‘/dev/mapper/root‘,mountpoint=‘/‘,fstype=‘ext4‘,opts=‘rw,errors=remount-ro‘),sdiskpart(device=‘/dev/sda1‘,mountpoint=‘/boot‘,fstype=‘ext2‘,opts=‘rw‘)] >>> psutil.disk_usage(‘/‘) sdiskusage(total=42273669120,used=17241096192,free=22885195776,percent=40.8) >>> 默认disk_io_counters方法获取的是硬盘总的io数和读写信息,如果需要获取单个分区的io和读写信息加上"perdisk=True"参数。 >>> psutil.disk_io_counters() sdiskio(read_count=638190,write_count=77080153,read_bytes=16037795840,write_bytes=1628871606272,read_time=2307367,write_time=1777841305) >>> psutil.disk_io_counters(perdisk=True) {‘vdb1‘: sdiskio(read_count=312,write_count=0,read_bytes=1238016,write_bytes=0,read_time=95,write_time=0),‘vda1‘: sdiskio(read_count=637878,write_count=77080257,read_bytes=16036557824,write_bytes=1628873314304,read_time=2307272,write_time=1777841879)} >>> 4.网络信息: ?网络io和磁盘io使用方法差不多,主要使用net_io_counters方法,如果需要获取单个网卡的io信息,加上pernic=True参数。 #获取网络总的io情况 >>> >>> psutil.net_io_counters() snetio(bytes_sent=525490132009,bytes_recv=409145642892,packets_sent=948527563,packets_recv=778182181,errin=0,errout=0,dropin=0,dropout=0) #获取网卡的io情况 >>> >>> psutil.net_io_counters(pernic=True) {‘lo‘: snetio(bytes_sent=56524704027,bytes_recv=56524704027,packets_sent=33602236,packets_recv=33602236,dropout=0),‘eth0‘: snetio(bytes_sent=468966480940,bytes_recv=352622081327,packets_sent=914930488,packets_recv=744583332,dropout=0)} >>> 5.其他系统信息: 1.获取开机时间 ##以linux时间格式返回,可以使用时间戳转换 >>> psutil.boot_time() 1496647567.0 #转换成自然时间格式 >>> psutil.boot_time() 1496647567.0 >>> datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S") ‘2017-06-05 15: 26: 07‘ >>> 2.查看系统全部进程 >>> psutil.pids() [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,46,47,48,49,50,51,52,53,60,61,63,64,65,97,98,279,280,331,398,481,676,693,769,845,848,1023,1085,1108,1355,1366,1457,1474,1475,1494,1541,1543,1545,1546,1548,1550,1552,2829,12436,12913,13129,16022,16029,16030,16031,16032,16033,16518,16520,17088,17124,19203,25382,32679] 3.查看单个进程
?查看系统硬件脚本: #!/usr/bin/env python 2 #coding:utf-8 3 4 import psutil 5 import datetime 6 import time 7 8 # 当前时间 9 now_time = time.strftime(‘%Y-%m-%d-%H:%M:%S‘,time.localtime(time.time())) 10 print(now_time) 11 12 # 查看cpu物理个数的信息 13 print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False)) 14 15 #CPU的使用率 16 cpu = (str(psutil.cpu_percent(1))) + ‘%‘ 17 print(u"cup使用率: %s" % cpu) 18 19 #查看内存信息,剩余内存.free 总共.total 20 #round()函数方法为返回浮点数x的四舍五入值。 21 22 free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0),2)) 23 total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0),2)) 24 memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total) 25 print(u"物理内存: %s G" % total) 26 print(u"剩余物理内存: %s G" % free) 27 print(u"物理内存使用率: %s %%" % int(memory * 100)) 28 # 系统启动时间 29 print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")) 30 31 # 系统用户 32 users_count = len(psutil.users()) 33 # 34 # >>> for u in psutil.users(): 35 # ... print(u) 36 # ... 37 # suser(name=‘root‘,terminal=‘pts/0‘,host=‘61.135.18.162‘,started=1505483904.0) 38 # suser(name=‘root‘,terminal=‘pts/5‘,started=1505469056.0) 39 # >>> u.name 40 # ‘root‘ 41 # >>> u.terminal 42 # ‘pts/5‘ 43 # >>> u.host 44 # ‘61.135.18.162‘ 45 # >>> u.started 46 # 1505469056.0 47 # >>> 48 49 users_list = ",".join([u.name for u in psutil.users()]) 50 print(u"当前有%s个用户,分别是 %s" % (users_count,users_list)) 51 52 #网卡,可以得到网卡属性,连接数,当前流量等信息 53 net = psutil.net_io_counters() 54 bytes_sent = ‘{0:.2f} Mb‘.format(net.bytes_recv / 1024 / 1024) 55 bytes_rcvd = ‘{0:.2f} Mb‘.format(net.bytes_sent / 1024 / 1024) 56 print(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd,bytes_sent)) 57 58 io = psutil.disk_partitions() 59 # print(io) 60 # print("io[-1]为",io[-1]) 61 #del io[-1] 62 63 print(‘-----------------------------磁盘信息---------------------------------------‘) 64 65 print("系统磁盘信息:" + str(io)) 66 67 for i in io: 68 o = psutil.disk_usage(i.device) 69 print("总容量:" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G") 70 print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G") 71 print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G") 72 73 print(‘-----------------------------进程信息-------------------------------------‘) 74 # 查看系统全部进程 75 for pnum in psutil.pids(): 76 p = psutil.Process(pnum) 77 print(u"进程名 %-20s 内存利用率 %-18s 进程状态 %-10s 创建时间 %-10s " 78 % (p.name(),p.memory_percent(),p.status(),p.create_time())) ? ? 以上是psutil模块获取linux系统基础信息的几个方法,大概常用的数据就这些。当然其他用法还有很多,详情可以参考他的官方文档。 网址:http://pythonhosted.org/psutil/ ?http://www.cnblogs.com/liu-yao/p/5678157.html http://www.sijitao.net/2043.html ? ?http://www.cnblogs.com/luomingchuan/p/3777269.html http://www.sijitao.net/2016.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |