You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python第三方API持续获取Linux系统的CPU与内存利用率?

嘿,我刚好碰到过类似的场景,给你几个靠谱的方案,再也不用头疼写正则解析top的输出啦!

首选方案:用psutil结合远程执行(结构化数据直接拿)

psutil是Python生态里超好用的系统监控库,能直接返回CPU、内存、磁盘等各种结构化的性能数据,完全不用自己去抠命令输出的字符串。不过因为是远程设备,我们可以通过paramiko在远程机器上跑一段psutil的代码,把结果以JSON格式传回来本地解析就行。

步骤走一遍:

  1. 先给远程机器装psutil
    用你现有的paramiko连接,先执行安装命令:

    stdin, stdout, stderr = ssh.exec_command('pip install psutil')
    # 可以打印输出确认安装是否成功
    print(stdout.read().decode())
    print(stderr.read().decode())
    
  2. 远程执行psutil脚本拿数据
    我们写一段Python代码,让远程机器执行后输出JSON格式的性能数据,本地直接解析就行:

    import json
    import paramiko
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('160.48.199.99', port=22, username='root', password='')
    
    # 构造要在远程执行的psutil代码
    remote_script = """
    import psutil
    import json
    
    # 获取CPU利用率(取1秒内的平均值,避免瞬时值不准)
    cpu_percent = psutil.cpu_percent(interval=1)
    # 获取内存详细信息
    mem_info = psutil.virtual_memory()
    # 顺便拿个磁盘根目录的使用情况(可选,按需加)
    disk_info = psutil.disk_usage('/')
    
    # 整理成易读的字典
    performance_data = {
        'cpu_usage_percent': cpu_percent,
        'memory_total_gb': round(mem_info.total / (1024**3), 2),
        'memory_used_gb': round(mem_info.used / (1024**3), 2),
        'memory_usage_percent': mem_info.percent,
        'disk_total_gb': round(disk_info.total / (1024**3), 2),
        'disk_used_gb': round(disk_info.used / (1024**3), 2),
        'disk_usage_percent': disk_info.percent
    }
    
    print(json.dumps(performance_data))
    """
    
    # 执行远程脚本(注意转义引号)
    stdin, stdout, stderr = ssh.exec_command(f'python3 -c "{remote_script.replace('"', '\\"')}"')
    output = stdout.read().decode().strip()
    error = stderr.read().decode().strip()
    
    if error:
        print(f"执行出错啦: {error}")
    else:
        # 解析JSON结果,直接用数据
        perf_data = json.loads(output)
        print("当前设备性能数据:")
        print(f"CPU利用率: {perf_data['cpu_usage_percent']}%")
        print(f"内存利用率: {perf_data['memory_usage_percent']}% (已用 {perf_data['memory_used_gb']}GB / 总 {perf_data['memory_total_gb']}GB)")
        print(f"磁盘利用率: {perf_data['disk_usage_percent']}% (已用 {perf_data['disk_used_gb']}GB / 总 {perf_data['disk_total_gb']}GB)")
    
    ssh.close()
    
备选方案:用Fabric简化操作

Fabric是基于paramiko的更高层框架,把远程执行的操作封装得更简洁,结合psutil用起来更顺手:

操作步骤:

  1. 本地先装Fabric
    打开命令行执行:

    pip install fabric
    
  2. Fabric示例代码

    from fabric import Connection
    import json
    
    # 建立远程连接
    conn = Connection(
        host='160.48.199.99',
        user='root',
        connect_kwargs={'password': ''}
    )
    
    # 先确保远程机器有psutil
    conn.run('pip install psutil', warn=True)
    
    # 执行监控脚本,直接拿结果
    result = conn.run("""
    import psutil
    import json
    data = {
        'cpu_usage': psutil.cpu_percent(1),
        'memory': psutil.virtual_memory()._asdict()
    }
    print(json.dumps(data))
    """, hide=True, shell=False, executable='python3')
    
    # 解析结果
    perf_data = json.loads(result.stdout)
    print(f"CPU利用率: {perf_data['cpu_usage']}%")
    print(f"内存利用率: {perf_data['memory']['percent']}%")
    print(f"已用内存: {round(perf_data['memory']['used']/1024**3, 2)}GB")
    
    # 关闭连接
    conn.close()
    
为啥不直接解析top?

说实话,top -b -n 1确实能输出非交互式的结果,但不同Linux发行版的top输出格式可能有差异,写正则匹配很容易踩坑,万一后续系统升级输出变了,脚本就崩了。而psutil返回的是结构化的数据,直接就能用,还能轻松扩展获取磁盘、网络、进程等更多信息,维护起来省心太多了。


内容的提问来源于stack exchange,提问作者Pawankumar Dubey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:05:15