Linux 系统信息获取工具 - 查看 CPU、内存、负载等状态
Linux 系统信息获取工具
本程序通过读取 /proc 文件系统获取 Linux 系统的各种状态信息,并输出到命令行界面。
获取信息
程序可以获取以下信息:
- CPU 信息:
- 类型
- 型号
- 内核版本
- 系统启动时间:
- 从系统启动至今的时间
- 内存信息:
- 总容量
- 当前可用内存量
- 系统平均负载:
- 1分钟、5分钟、15分钟的平均负载
- 支持的文件系统类型:
- 系统支持的所有文件系统类型
- 正在使用的模块:
- 系统当前正在使用的模块信息
实现步骤
- 读取
/proc/cpuinfo文件,解析出 CPU 类型、型号、内核版本等信息。 - 读取
/proc/uptime文件,解析出从系统启动至今的时间。 - 读取
/proc/meminfo文件,解析出内存总容量及当前可用内存量。 - 读取
/proc/loadavg文件,解析出系统平均负载。 - 读取
/proc/filesystems文件,解析出支持的文件系统类型。 - 读取
/proc/modules文件,解析出系统正在使用的 module 信息。 - 将以上信息输出到命令行界面。
代码实现
import os
# 读取 /proc/cpuinfo 文件,解析出 CPU 类型、型号、内核版本等信息
def get_cpu_info():
with open('/proc/cpuinfo', 'r') as f:
cpu_info = f.readlines()
for line in cpu_info:
if line.startswith('model name'):
cpu_type = line.split(':')[1].strip()
elif line.startswith('model'):
cpu_model = line.split(':')[1].strip()
elif line.startswith('Linux'):
kernel_version = line.split()[2]
return cpu_type, cpu_model, kernel_version
# 读取 /proc/uptime 文件,解析出从系统启动至今的时间
def get_uptime():
with open('/proc/uptime', 'r') as f:
uptime = f.readline().split()[0]
return int(float(uptime))
# 读取 /proc/meminfo 文件,解析出内存总容量及当前可用内存量
def get_mem_info():
with open('/proc/meminfo', 'r') as f:
mem_info = f.readlines()
for line in mem_info:
if line.startswith('MemTotal'):
mem_total = int(line.split(':')[1].strip()[:-3])
elif line.startswith('MemAvailable'):
mem_avail = int(line.split(':')[1].strip()[:-3])
return mem_total, mem_avail
# 读取 /proc/loadavg 文件,解析出系统平均负载
def get_loadavg():
with open('/proc/loadavg', 'r') as f:
loadavg = f.readline().split()[:3]
return loadavg
# 读取 /proc/filesystems 文件,解析出支持的文件系统类型
def get_filesystems():
with open('/proc/filesystems', 'r') as f:
filesystems = f.readlines()
return [fs.strip() for fs in filesystems]
# 读取 /proc/modules 文件,解析出系统正在使用的 module 信息
def get_modules():
with open('/proc/modules', 'r') as f:
modules = f.readlines()
return [mod.split()[0] for mod in modules]
if __name__ == '__main__':
cpu_type, cpu_model, kernel_version = get_cpu_info()
uptime = get_uptime()
mem_total, mem_avail = get_mem_info()
loadavg = get_loadavg()
filesystems = get_filesystems()
modules = get_modules()
print('CPU Type: ' + cpu_type)
print('CPU Model: ' + cpu_model)
print('Kernel Version: ' + kernel_version)
print('Uptime: ' + str(uptime) + ' seconds')
print('Memory Total: ' + str(mem_total) + ' GB')
print('Memory Available: ' + str(mem_avail) + ' GB')
print('Load Average (1min, 5min, 15min): ' + ', '.join(loadavg))
print('Supported Filesystems: ' + ', '.join(filesystems))
print('Modules in Use: ' + ', '.join(modules))
使用方法
- 将代码保存为 Python 文件,例如
system_info.py。 - 在命令行中运行该文件:
python system_info.py
程序将会输出系统信息到命令行界面。
注意事项
- 本程序需要运行在 Linux 系统上。
- 程序需要具有读取
/proc文件系统的权限。 - 程序输出的信息可能会因为系统环境不同而有所差异。
原文地址: https://www.cveoy.top/t/topic/oqjX 著作权归作者所有。请勿转载和采集!