在Python中获取Linux系统信息可以通过多种方法,以下是几种常见的方法:
方法一:使用psutil模块
psutil是一个跨平台的库,用于获取系统信息,如CPU、内存、磁盘、网络等信息。
import psutildef get_host_info():host_name = socket.gethostname()return {'host_name': host_name}def get_cpu_state():cpu_count = psutil.cpu_count(logical=False)cpu_percent = str(psutil.cpu_percent(interval=1)) + '%'return {'cpu_count': cpu_count, 'cpu_percent': cpu_percent}def get_memory_state():mem = psutil.virtual_memory()mem_total = mem.total / 1024 / 1024mem_free = mem.available / 1024 / 1024mem_percent = f'{mem.percent}%'return {'mem_total': mem_total, 'mem_free': mem_free, 'mem_percent': mem_percent}def get_disk_state():disk_stat = psutil.disk_usage('/')return {'disk_total': disk_stat.total / 1024 / 1024, 'disk_free': disk_stat.free / 1024 / 1024, 'disk_percent': disk_stat.percent}
方法二:使用`/proc`文件系统
Linux的`/proc`文件系统包含了大量的系统信息,可以通过读取这些文件来获取系统状态。
def memory_stat():mem = {}with open('/proc/meminfo', 'r') as f:lines = f.readlines()for line in lines:key, value = line.split(':')mem[key.strip()] = int(value.strip())return memdef cpu_stat():cpu = []with open('/proc/cpuinfo', 'r') as f:lines = f.readlines()for line in lines:key, value = line.split(':')cpu.append({key.strip(): value.strip()})return cpudef net_stat():net = []with open('/proc/net/dev', 'r') as f:lines = f.readlines()for line in lines:if 'eth0' in line: 获取特定网卡的流量信息parts = line.split()net.append({'interface': parts, 'rx': parts, 'tx': parts})return net
方法三:使用`subprocess`模块
`subprocess`模块允许你执行系统命令并获取输出。
from subprocess import Popen, PIPEdef getIfconfig():p = Popen(['ifconfig'], stdout=PIPE)data = p.stdout.read().decode()return datadef getDmi():p = Popen(['dmidecode'], stdout=PIPE)data = p.stdout.read().decode()dmi_dic = {}for line in data.split('\n'):if 'Product Name' in line:dmi_dic['Product Name'] = line.split(':').strip()if 'Serial Number' in line:dmi_dic['Serial Number'] = line.split(':').strip()return dmi_dic
执行脚本
确保你的Python脚本具有执行权限,使用`chmod +x your-script.py`,然后你可以通过`./your-script.py`来执行脚本。
以上方法可以帮助你获取Linux系统的各种信息,包括主机名、CPU状态、内存状态、磁盘状态以及网络流量等。

