psutil简介
psutil是一个开源切跨平台的库,其提供了便利的函数用来获取才做系统的信息,比如CPU,内存,磁盘,网络等。此外,psutil还可以用来进行进程管理,包括判断进程是否存在、获取进程列表、获取进程详细信息等。而且psutil还提供了许多命令行工具提供的功能,包括:ps,top,lsof,netstat,ifconfig, who,df,kill,free,nice,ionice,iostat,iotop,uptime,pidof,tty,taskset,pmap
程序结果展示
psutil使用目的
通过python脚本了解服务器的使用情况和一些基础参数,并自定义功能
psutil获取系统信息和参数
1.cpu
核心数
使用率
2.内存
总量
使用量
空闲量
使用率
3.磁盘
各个分区挂载点使用情况和百分比
4.网络
网卡对应网络信息
5.其他
系统启动时间
系统1,5,15分钟平均负载
系统对外提供了哪些服务
psutil各功能代码的实现
1.cpu信息相关
def get_cpuinfo():
physical_nums = psutil.cpu_count(logical=False)
logical_nums = psutil.cpu_count()
cpu_percents = psutil.cpu_percent(interval=1)
return dict(physical_nums=physical_nums, logical_nums=logical_nums, cpu_percents=cpu_percents)
2.内存信息相关
def get_memoryinfo():
virtual_mem = psutil.virtual_memory()
mem_total = byte2human(virtual_mem.total)
mem_used = byte2human(virtual_mem.used)
mem_free = byte2human(virtual_mem.free + virtual_mem.buffers + virtual_mem.cached)
mem_percent = virtual_mem.percent
return dict(mem_total=mem_total, mem_used=mem_used, mem_free=mem_free, mem_percent=mem_percent)
3.磁盘信息相关
def get_diskinfo():
data={}
for i in psutil.disk_partitions():
disk_usage = psutil.disk_usage(i.mountpoint)
disk_total = byte2human(disk_usage.total)
disk_used = byte2human(disk_usage.used)
disk_free = byte2human(disk_usage.free)
disk_percent = byte2human(disk_usage.percent)
disk_mount = i
data[i]={'disk_total':disk_total,'disk_used':disk_used,'disk_free':disk_free,'disk_percent':disk_percent}
return data
4.网络信息相关
def get_netinfo():
data={}
for i,k in psutil.net_if_addrs().items():
if len(k) >= 3:
data[i] = k[0].address
return data
5.其他信息相关
1)系统启动时间
def get_sysboottime():
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
return dict(boot_time=boot_time)
2)系统负载并判断运行状态是否良好
def get_sysload():
sysload = psutil.getloadavg()
return dict(sysload=sysload)
3)对外提供的端口和服务名
def get_port2service():
data = {}
for proc in psutil.process_iter():
for x in proc.connections():
if x.status == 'LISTEN' and x.laddr.ip not in ('127.0.0.1','::','::1'):
if proc.name() not in data:
data[proc.name()]=[x.laddr.port]
else:
data[proc.name()].append(x.laddr.port)
return data
6.字节转换,方便理解
实际使用中可以发现有许多数据是以字节形式呈现的,不方便读取,因此写个方法将数值转换成K、M、G、T等人类方便理解的呈现方式
def byte2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E')
prefix = {}
for i, k in enumerate(symbols):
prefix[k] = 1<< (i+1) * 10
for k in reversed(symbols):
if n >= prefix[k]:
value = float(n) / prefix[k]
return '%.1f%s' % (value, k)
return '%sB' % n
python脚本运行条件
1) 安装gcc编译器和python-devel安装包
2) 安装第三方库psutil,prettytable
# yum install gcc python-devel -y
# pip install psutil
# pip install prettytable
程序代码
#! -*- encoding=utf-8 -*-
# author: ZhaiMingyu
# mail: 276622709@qq.com
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import psutil
import datetime, time
import prettytable as pt
def get_cpuinfo():
physical_nums = psutil.cpu_count(logical=False)
logical_nums = psutil.cpu_count()
cpu_percents = psutil.cpu_percent(interval=1)
return dict(physical_nums=physical_nums, logical_nums=logical_nums, cpu_percents=cpu_percents)
def get_memoryinfo():
virtual_mem = psutil.virtual_memory()
mem_total = byte2human(virtual_mem.total)
mem_used = byte2human(virtual_mem.used)
mem_free = byte2human(virtual_mem.free + virtual_mem.buffers + virtual_mem.cached)
mem_percent = virtual_mem.percent
return dict(mem_total=mem_total, mem_used=mem_used, mem_free=mem_free, mem_percent=mem_percent)
def get_diskinfo():
data={}
for i in psutil.disk_partitions():
disk_usage = psutil.disk_usage(i.mountpoint)
disk_total = byte2human(disk_usage.total)
disk_used = byte2human(disk_usage.used)
disk_free = byte2human(disk_usage.free)
disk_percent = disk_usage.percent
disk_mount = i.mountpoint
data[disk_mount]={'disk_total':disk_total,'disk_used':disk_used,'disk_free':disk_free,'disk_percent':disk_percent}
return data
def get_netinfo():
data={}
for i,k in psutil.net_if_addrs().items():
if len(k) >= 3:
data[i] = k[0].address
return data
def get_sysboottime():
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
return dict(boot_time=boot_time)
def get_sysload():
sysload = psutil.getloadavg()
return dict(sysload=sysload)
def get_port2service():
data = {}
for proc in psutil.process_iter():
for x in proc.connections():
if x.status == 'LISTEN' and x.laddr.ip not in ('127.0.0.1','::','::1'):
if proc.name() not in data:
data[proc.name()]=[x.laddr.port]
else:
data[proc.name()].append(x.laddr.port)
return data
def byte2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E')
prefix = {}
for i, k in enumerate(symbols):
prefix[k] = 1<< (i+1) * 10
for k in reversed(symbols):
if n >= prefix[k]:
value = float(n) / prefix[k]
return '%.1f%s' % (value, k)
return '%sB' % n
def main():
print('~~~~~~~~~~~~~~~~~~~ cpu info ~~~~~~~~~~~~~~~~~~')
gc = get_cpuinfo()
tb1 = pt.PrettyTable()
tb1.field_names = ['cpu核心数','cpu核心数(含超线程)','cpu使用率%']
tb1.add_row([gc['physical_nums'],gc['logical_nums'],gc['cpu_percents']])
print(tb1)
print()
print('~~~~~~~~~~~~~~~~~~~~ memory info ~~~~~~~~~~~~~~~~~~~~')
gm = get_memoryinfo()
tb2 = pt.PrettyTable()
tb2.field_names = ['内存总量','内存使用量','内存空间量','内存使用百分比']
tb2.add_row([gm['mem_total'],gm['mem_used'],gm['mem_free'],gm['mem_percent']])
print(tb2)
print()
print('~~~~~~~~~~~~~~~~~~ disk info ~~~~~~~~~~~~~~~~~~~~')
gd = get_diskinfo()
tb3 = pt.PrettyTable()
tb3.field_names = ['挂载点','容量','已用','可用','已用百分比']
for i in gd:
tb3.add_row([i,gd[i]['disk_total'],gd[i]['disk_used'],gd[i]['disk_free'],gd[i]['disk_percent']])
print(tb3)
print()
print('~~~~~~~~~~~~~~~~~~~~~~ net info ~~~~~~~~~~~~~~~~~~~~~~~')
gn = get_netinfo()
tb4 = pt.PrettyTable()
column_names=['列表项']
for i in range(len(gn)):
column_names.append('')
tb4.add_column(column_names[0],['网卡','IP'])
num = 1
for eth, ip_address in gn.items():
tb4.add_column(column_names[num],[eth,ip_address])
num += 1
print(tb4)
print()
print('~~~~~~~~~~~系统启动时间~~~~~~~~~~~')
gs = get_sysboottime()
print('系统启动时间:%s' % gs['boot_time'])
print()
print('~~~~~~~~~~~~~~~~~~~系统cpu负载~~~~~~~~~~~~~~~~~~')
sysload = get_sysload()
print('cpu平均每分钟负载:%s cpu平均5分钟负载:%s cpu平均15分钟负载:%s' % sysload['sysload'])
if sysload['sysload'][2] < 0.7*gc['logical_nums']:
print('cpu负载状况良好')
elif 0.7*gc['logical_nums'] <= sysload['sysload'][2] < 1**gc['logical_nums']:
print('cpu负载接近饱满')
else:
print('cpu负载过高')
print()
print('~~~~~~~~~~~~~~~~~~~系统对外提供的服务及端口~~~~~~~~~~~~~~~~~~')
gp = get_port2service()
tb5 = pt.PrettyTable()
column_names1=['列表项']
num1 = 1
for k in range(len(gp)):
column_names1.append('')
tb5.add_column(column_names1[0],['程序名','端口'])
for proc, port in gp.items():
tb5.add_column(column_names1[num1],[proc,port])
num1 += 1
print(tb5)
if __name__ == '__main__':
main()
声明:本博客的原创文章,都是本人平时学习所做的笔记,转载请标注出处,谢谢合作。