Python获取Linux系统信息的三种实现方案
本文详细介绍Python获取Linux系统信息的三种常用方法。第一种利用psutil模块直接调用API,代码简洁高效;第二种通过读取/proc文件系统手动解析CPU、内存和磁盘数据,适合理解底层原理;第三种借助subprocess模块执行系统命令如top或ifconfig,适用于需要特定命令输出的场景。文中提供完整代码示例,帮助开发者根据实际需求选择合适方案。
使用psutil模块获取系统信息
第一种方法是通过安装并使用psutil模块来实现。该模块提供了跨平台的系统监控接口,能够方便地获取主机名、CPU状态、内存使用情况以及磁盘信息等关键数据。这种方法代码量少,可读性强,且无需处理复杂的系统文件解析逻辑,是大多数场景下的首选方案。
#!usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import psutil
class NodeResource(object):
def get_host_info(self):
host_name = socket.gethostname()
return {'host_name':host_name}
def get_cpu_state(self):
cpu_count = psutil.cpu_count(logical=False)
cpu_percent =(str)(psutil.cpu_percent(1))+'%'
return {'cpu_count':cpu_count,'cpu_percent':cpu_percent}
def get_memory_state(self):
mem = psutil.virtual_memory()
mem_total = mem.total / 1024 / 1024
mem_free = mem.available /1024/1024
mem_percent = '%s%%'%mem.percent
return {'mem_toal':mem_total,'mem_free':mem_free,'mem_percent':mem_percent}
def get_disk_state(self):
disk_stat = psutil.disk_usage('/')
disk_total = disk_stat.total
disk_free = disk_stat.free
disk_percent = '%s%%'%disk_stat.percent
return {'mem_toal': disk_total, 'mem_free': disk_free, 'mem_percent': disk_percent}
通过/proc文件系统解析系统数据
第二种方法涉及直接读取Linux系统的/proc虚拟文件系统。通过解析/proc/stat文件计算CPU使用率,读取/proc/meminfo获取内存状态,以及访问/proc/diskstats或挂载点信息来统计磁盘使用情况。这种方法不依赖第三方库,但需要开发者手动处理数据解析和计算逻辑,适合对底层机制有深入了解的场景。
#!usr/bin/env python
# -*- coding: utf-8 -*-
import time
import os
from multiprocessing import cpu_count
class NodeResource(object):
def usage_percent(self,use, total):
# 返回百分占比
try:
ret = int(float(use)/ total * 100)
except ZeroDivisionError:
raise Exception("ERROR - zero division error")
return '%s%%'%ret
@property
def cpu_stat(self,interval = 1):
cpu_num = cpu_count()
with open("/proc/stat", "r") as f:
line = f.readline()
spl = line.split(" ")
worktime_1 = sum([int(i) for i in spl[2:]])
idletime_1 = int(spl[5])
time.sleep(interval)
with open("/proc/stat", "r") as f:
line = f.readline()
spl = line.split(" ")
worktime_2 = sum([int(i) for i in spl[2:]])
idletime_2 = int(spl[5])
dworktime = (worktime_2 - worktime_1)
didletime = (idletime_2 - idletime_1)
cpu_percent = self.usage_percent(dworktime - didletime,didletime)
return {'cpu_count':cpu_num,'cpu_percent':cpu_percent}
@property
def disk_stat(self):
hd = {}
disk = os.statvfs("/")
hd['available'] = disk.f_bsize * disk.f_bfree
hd['capacity'] = disk.f_bsize * disk.f_blocks
hd['used'] = hd['capacity'] - hd['available']
hd['used_percent'] = self.usage_percent(hd['used'], hd['capacity'])
return hd
@property
def memory_stat(self):
mem = {}
with open("/proc/meminfo") as f:
for line in f:
line = line.strip()
if len(line) < 2: continue
name = line.split(':')[0]
var = line.split(':')[1].split()[0]
mem[name] = long(var) * 1024.0
mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
mem['used_percent'] = self.usage_percent(mem['MemUsed'],mem['MemTotal'])
return {'MemUsed':mem['MemUsed'],'MemTotal':mem['MemTotal'],'used_percent':mem['used_percent']}
nr = NodeResource()
print nr.cpu_stat
print '=================='
print nr.disk_stat
print '=================='
print nr.memory_stat
利用subprocess执行系统命令
第三种方法利用subprocess模块执行Linux系统命令,如ifconfig、dmidecode、top等,并捕获其标准输出进行解析。这种方式可以获取命令特有的详细信息,例如网络接口的具体配置或硬件层面的DMI信息。虽然灵活性高,但依赖于特定命令的存在和输出格式,且执行效率相对较低,通常用于需要获取特定命令详细输出的情况。
from subprocess import Popen, PIPE
import os,sys
''' 获取 ifconfig 命令的输出 '''
def getIfconfig():
p = Popen(['ifconfig'], stdout = PIPE)
data = p.stdout.read()
return data
''' 获取 dmidecode 命令的输出 '''
def getDmi():
p = Popen(['dmidecode'], stdout = PIPE)
data = p.stdout.read()
return data
''' 根据空行分段落 返回段落列表'''
def parseData(data):
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line + '\n'
else:
new_line += line + '\n'
parsed_data.append(new_line)
return [i for i in parsed_data if i]
''' 根据输入的段落数据分析出ifconfig的每个网卡ip信息 '''
def parseIfconfig(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if not i.startswith('lo')]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic['ip'] = ipaddr
return dic
''' 根据输入的dmi段落数据 分析出指定参数 '''
def parseDmi(parsed_data):
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
dmi_dic = dict([i.strip().split(':') for i in parsed_data])
dic['vender'] = dmi_dic['Manufacturer'].strip()
dic['product'] = dmi_dic['Product Name'].strip()
dic['sn'] = dmi_dic['Serial Number'].strip()
return dic
''' 获取Linux系统主机名称 '''
def getHostname():
with open('/etc/sysconfig/network') as fd:
for line in fd:
if line.startswith('HOSTNAME'):
hostname = line.split('=')[1].strip()
break
return {'hostname':hostname}
''' 获取Linux系统的版本信息 '''
def getOsVersion():
with open('/etc/issue') as fd:
for line in fd:
osver = line.strip()
break
return {'osver':osver}
''' 获取CPU的型号和CPU的核心数 '''
def getCpu():
num = 0
with open('/proc/cpuinfo') as fd:
for line in fd:
if line.startswith('processor'):
num += 1
if line.startswith('model name'):
cpu_model = line.split(':')[1].strip().split()
cpu_model = cpu_model[0] + ' ' + cpu_model[2] + ' ' + cpu_model[-1]
return {'cpu_num':num, 'cpu_model':cpu_model}
''' 获取Linux系统的总物理内存 '''
def getMemory():
with open('/proc/meminfo') as fd:
for line in fd:
if line.startswith('MemTotal'):
mem = int(line.split()[1].strip())
break
mem = '%.f' % (mem / 1024.0) + ' MB'
return {'Memory':mem}
if __name__ == '__main__':
dic = {}
data_ip = getIfconfig()
parsed_data_ip = parseData(data_ip)
ip = parseIfconfig(parsed_data_ip)
data_dmi = getDmi()
parsed_data_dmi = parseData(data_dmi)
dmi = parseDmi(parsed_data_dmi)
hostname = getHostname()
osver = getOsVersion()
cpu = getCpu()
mem = getMemory()
dic.update(ip)
dic.update(dmi)
dic.update(hostname)
dic.update(osver)
dic.update(cpu)
dic.update(mem)
''' 将获取到的所有数据信息并按简单格式对齐显示 '''
for k,v in dic.items():
print '%-10s:%s' % (k, v)
from subprocess import Popen, PIPE
import time
''' 获取 ifconfig 命令的输出 '''
# def getIfconfig():
# p = Popen(['ipconfig'], stdout = PIPE)
# data = p.stdout.read()
# data = data.decode('cp936').encode('utf-8')
# return data
#
# print(getIfconfig())
p = Popen(['top -n 2 -d |grep Cpu'],stdout= PIPE,shell=True)
data = p.stdout.read()
info = data.split('\n')[1]
info_list = info.split()
cpu_percent ='%s%%'%int(float(info_list[1])+float(info_list[3]))
print cpu_percent
综上所述,Python获取Linux系统信息主要可通过psutil模块、/proc文件系统解析以及subprocess执行系统命令这三种途径实现。开发者可根据项目对依赖库的限制、性能要求以及所需信息的详细程度,选择最合适的方法。更多Python相关技术内容,欢迎持续关注本站后续更新。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













