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

如何开发可获取Linux系统详情的API?求入门实施指导

入门方向与实施思路

一、先明确API的适用场景

  • 如果你的API只需要获取自身所在Linux主机的系统详情:直接用Python的subprocess调用系统命令是最直接的方案,完全可行,不存在API里不能用的问题。
  • 如果需要获取多台远程Linux主机的系统详情:SSH是可行的方案,只要处理好认证和连接逻辑,API里完全可以用。

二、本地API快速实现思路

  1. 选一个轻量的Python API框架:比如FastAPI或者Flask,上手快,适合快速搭建接口。
  2. 用subprocess调用系统命令获取数据:
    常用的系统信息命令:
    • CPU信息:cat /proc/cpuinfo
    • 内存信息:free -h
    • 磁盘信息:df -h
    • 系统版本:cat /etc/os-release
      示例代码片段:
    import subprocess
    from fastapi import FastAPI
    
    app = FastAPI()
    
    def run_command(cmd):
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            return result.stdout.strip()
        else:
            return f"Error: {result.stderr.strip()}"
    
    @app.get("/system/cpu")
    def get_cpu_info():
        return {"cpu_model": run_command("cat /proc/cpuinfo | grep 'model name' | head -1")}
    
    @app.get("/system/memory")
    def get_memory_info():
        return {"memory_status": run_command("free -h")}
    
  3. 封装数据格式:把命令输出的文本转换成JSON格式,方便调用方解析,也可以用psutil库替代shell命令——这是专门的系统监控库,直接通过Python方法获取数据,更稳定易处理。

三、远程多主机API实现思路

如果要支持远程主机,用Python的paramiko库实现SSH连接完全可行:

  1. 安装依赖:pip install paramiko
  2. 核心逻辑示例:
    import paramiko
    from fastapi import FastAPI
    
    app = FastAPI()
    
    def fetch_remote_info(host, username, password=None, key_path=None):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            # 优先用密钥认证,更安全
            if key_path:
                private_key = paramiko.RSAKey.from_private_key_file(key_path)
                ssh.connect(host, username=username, pkey=private_key)
            else:
                ssh.connect(host, username=username, password=password)
            # 执行命令获取系统信息
            _, stdout, stderr = ssh.exec_command("cat /etc/os-release")
            output = stdout.read().decode().strip()
            return {"system_info": output}
        except Exception as e:
            return {"error": str(e)}
        finally:
            ssh.close()
    
    @app.get("/remote/system")
    def get_remote_system(host: str, username: str, password: str = None, key_path: str = None):
        return fetch_remote_info(host, username, password, key_path)
    
  3. 关键注意事项:
    • 不要把密码硬编码在代码里,用环境变量或配置文件存储
    • 处理连接超时、认证失败等异常情况
    • 可以封装SSH连接池,避免频繁建立连接损耗性能

四、进阶优化建议

  • 用psutil替代subprocess:跨平台且无需调用shell命令,比如psutil.cpu_percent()、psutil.virtual_memory()直接返回结构化数据
  • 增加API权限控制:比如添加API密钥认证,防止未授权访问
  • 缓存静态信息:系统版本、CPU型号这类不会频繁变化的数据,缓存几分钟减少重复调用

内容的提问来源于stack exchange,提问作者Vilas R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:50:26