温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux Python中处理系统硬件信息获取

发布时间:2024-09-12 11:58:47 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在 Linux 系统中,可以使用 Python 的各种库来获取和处理硬件信息

  1. 使用 ossubprocess 模块执行系统命令并解析输出:
import os
import subprocess

def get_cpu_info():
    command = "lscpu"
    result = subprocess.run(command.split(), stdout=subprocess.PIPE)
    output = result.stdout.decode('utf-8')
    cpu_info = {}
    for line in output.split('\n'):
        if ':' in line:
            key, value = line.split(':', 1)
            cpu_info[key.strip()] = value.strip()
    return cpu_info

print(get_cpu_info())
  1. 使用 psutil 库获取系统和进程信息:

首先安装 psutil 库:

pip install psutil

然后使用以下代码获取 CPU、内存和磁盘信息:

import psutil

def get_system_info():
    system_info = {
        'cpu': {
            'count': psutil.cpu_count(),
            'percent': psutil.cpu_percent()
        },
        'memory': {
            'total': psutil.virtual_memory().total,
            'available': psutil.virtual_memory().available,
            'percent': psutil.virtual_memory().percent
        },
        'disk': {
            'total': psutil.disk_usage('/').total,
            'used': psutil.disk_usage('/').used,
            'percent': psutil.disk_usage('/').percent
        }
    }
    return system_info

print(get_system_info())
  1. 使用 py-cpuinfo 库获取详细的 CPU 信息:

首先安装 py-cpuinfo 库:

pip install py-cpuinfo

然后使用以下代码获取 CPU 信息:

import cpuinfo

def get_detailed_cpu_info():
    cpu_info = cpuinfo.get_cpu_info()
    return cpu_info

print(get_detailed_cpu_info())
  1. 使用 netifaces 库获取网络接口信息:

首先安装 netifaces 库:

pip install netifaces

然后使用以下代码获取网络接口信息:

import netifaces as ni

def get_network_interfaces():
    network_interfaces = {}
    for interface in ni.interfaces():
        addresses = ni.ifaddresses(interface)
        network_interfaces[interface] = {
            'ipv4': addresses.get(ni.AF_INET),
            'ipv6': addresses.get(ni.AF_INET6),
            'mac': addresses.get(ni.AF_LINK)
        }
    return network_interfaces

print(get_network_interfaces())

这些示例仅展示了如何使用 Python 获取硬件信息。根据需要,可以结合其他库或方法来获取更多详细信息。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI