table of Contents
Foreword
psutil is a cross-platform library, can easily obtain gold Cen systems utilization of system operation, including information on CPU, memory, disk, network, etc., it is mainly used in system monitoring, management, analysis, and system resource constraints and processes. It implements the functions of the same command-line tools, such as ps, top, lsof, netstat, ifconfig, who, free, etc.
Usually we get the information systems are often used to prepare the shell to achieve, such as access to the current total size of physical memory
[[email protected] ~]$ free -m
total used free shared buffers cached
Mem: 981 899 81 15 44 149
-/+ buffers/cache: 705 275
Swap: 1983 999 984
[[email protected] ~]$
Use python library of psutil get easier
So psutil is a third-party modules, you need to install
Windows:
pip3 install psutil
Linux:
wget https://pypi.python.org/packages/source/p/psutil/psutil-3.2.1.tar.gz --no-check-certificate
tar zxvf psutil-3.2.1.tar.gz
cd psutil-3.2.1
python3 setup.py install
Use as follows:
import psutil # 导入psutil模块
mem = psutil.virtual_memory() # 实例化出来mem对象
print(mem) # 查看完整内存信息
print(mem.total) # 查看内存总大小,单位是字节
print(mem.used) # 查看内存使用大小
After acquiring the size we can use the conversion tool to convert
Get System Performance Information
CPU
Linux operating system, CPU utilization has the following components:
- User Time: execution time percentage of user process
- System Time: kernel execution process and interrupt the percentage of time
- Wait IO: IO wait because the CPU is in IDLE (idle) state of the percentage of time
- Idle: CPU time percentages in the state space
print(psutil.cpu_times()) # 获取CPU 完整的信息
print(psutil.cpu_times().user) # 获取用户user的cpu时间比
print(psutil.cpu_count()) # 获取CPU 的逻辑个数
print(psutil.cpu_count(logical=False)) # 获取CPU 的物理个数
print(psutil.cpu_percent()) # 获取cpu的使用率
print(psutil.cpu_percent(1))
RAM
Linux operating system, memory utilization has the following components:
- total (total memory)
- used (the number of used memory)
- free (the number of free memory)
- buffers (buffer number used)
- cache (number of cache use)
- swap (Swap number used)
mem = psutil.virtual_memory() # 实例化出来mem对象
print(mem) # 查看完整内存信息
print(mem.total) # 查看内存总大小
print(mem.used) # 查看内存使用大小
Disk
In the system disk information, disk utilization, ie we pay more attention to IO information. Disk utilization can get psutil.disk_usage
method to get
print(psutil.disk_partitions()) # 获取磁盘完整信息
print(psutil.disk_usage("/")) # 获取分区的使用参数
print(psutil.disk_io_counters()) # 获取磁盘的读写信息
Internet Information
Network information comprises bytes_sent (number of bytes sent), the number of bytes received, etc.
print(psutil.net_io_counters()) # 获取完整的网络信息
Other information systems
In addition to several methods to obtain basic information about the system introduced above, psutil module also supports getting user login, boot time and other information
print(psutil.users()) # 获取当前登录系统的用户信息
print(psutil.boot_time()) # 获取开机时间,以时间戳格式返回
import datetime
res = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d" "%H:%M:%S")
print(res) # 格式化为人们看得懂的时间
System process management
Get the current system processes information, operation and maintenance personnel can make informed operational status of applications, including process start time, view or set the CPU affinity, memory usage, IO information, socket connections, threads, etc. This information can be showing a specified process is alive, resource utilization, for the developer's code optimization, fault location data to provide a good reference
Process Information
psutil process of obtaining information
print(psutil.pids()) # 获取所有进程PID,以列表形式返回
p = psutil.Process(9236) # 实例化一个对象,参数为一个进程ID
print(p.name()) # 通过name属性可以得到这个进程的名称
print(p.exe()) # 通过exe属性可以得到这个进程的路径
print(p.cwd()) # 通过cwd属性可以进入工作目录绝对路径
print(p.status()) # 通过status属性可以看到这个进程的状态
print(p.create_time()) # 通过create_time属性可以看到这个进程的创建时间,时间戳形式
print(p.uids()) # 通过uids属性可以看到进程的uid信息
print(p.gids()) # 通过gids属性可以看到进程的gid信息
print(p.cpu_times()) # 通过cpu_times可以看到user、system两个cpu的时间
print(p.cpu_affinity()) # 获取cpu亲和度,如果要设置亲和度,将cou号作为参数即可。
print(p.memory_percent()) # 通过memory_percent可以看到进程的内存利用率
print(p.memory_info()) # 通过memory_info可以看到进内存的rss、vms信息
print(p.io_counters()) # 通过io_counters可以看到进程的io信息
print(p.connections()) # 通过connections可以看到进程的socket连接数
print(p.num_threads()) # 通过num_threads可以看到进程开启的线程数
popen class
Popen role is to get the user started the application process information in order to track the progress of the program running state
from subprocess import PIPE
p = psutil.Popen(["python3 psutil_使用.py"],stdout=PIPE)
print(p.name())
print(p.username())
print(p.cpu_times)
View the system hardware little script
#!/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(u"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(u"物理内存: %s G" % total)
print(u"剩余物理内存: %s G" % free)
print(u"物理内存使用率: %s %%" % int(memory * 100))
# 系统启动时间
print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))
# 系统用户
users_count = len(psutil.users())
#
# >>> for u in psutil.users():
# ... print(u)
# ...
# suser(name='root', terminal='pts/0', host='61.135.18.162', started=1505483904.0)
# suser(name='root', terminal='pts/5', host='61.135.18.162', started=1505469056.0)
# >>> u.name
# 'root'
# >>> u.terminal
# 'pts/5'
# >>> u.host
# '61.135.18.162'
# >>> u.started
# 1505469056.0
# >>>
users_list = ",".join([u.name for u in psutil.users()])
print(u"当前有%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(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent))
io = psutil.disk_partitions()
# print(io)
# print("io[-1]为",io[-1])
#del io[-1]
print('-----------------------------磁盘信息---------------------------------------')
print("系统磁盘信息:" + str(io))
for i in io:
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")
print('-----------------------------进程信息-------------------------------------')
# 查看系统全部进程
for pnum in psutil.pids():
p = psutil.Process(pnum)
print(u"进程名 %-20s 内存利用率 %-18s 进程状态 %-10s 创建时间 %-10s " \
% (p.name(), p.memory_percent(), p.status(), p.create_time()))
硬件信息脚本