Ω₀⊂⊙∞⊂Ω · 确权锚点

跨平台命令执行适配器 · 架构白皮书

跨平台命令执行适配 · 统一执行平面
版本 V1.0 发布日期 2026年10月 文档密级 公开 DID DID-BR-000002
目录

DID-BR-000002 | Ω₀⊂⊙∞⊂Ω | ZONGYUAN-ROOT


一、问题定义

1.1 问题本质

在Windows PowerShell环境下通过SSH执行Linux Bash命令时,存在双层Shell解析冲突:

用户输入命令
    ↓
PowerShell解析(第一层)
    ↓ 引号/变量/特殊字符被PowerShell处理
SSH传递
    ↓
Bash解析(第二层)
    ↓ 再次解析,导致命令被破坏
执行失败

1.2 典型失败场景

场景命令示例失败原因
变量引用echo $HOMEPowerShell先展开$HOME为Windows路径
命令替换$(date)PowerShell尝试执行子表达式
多层引号awk '{print $1}'引号嵌套被PowerShell破坏
循环结构for i in ...; do ...; done分号和关键字被PowerShell解析
反引号echo \date\``PowerShell反引号是转义字符
Here文档<<EOF ... EOF多行命令传递失败

1.3 影响范围


二、解决方案架构

2.1 核心设计原则

  1. 脚本文件优先:复杂命令自动使用脚本文件方式,彻底规避转义问题
  2. 自动模式选择:根据命令复杂度自动选择执行模式
  3. 统一API:屏蔽底层Shell差异,提供标准化接口
  4. 可观测性:完整的执行日志和统计
  5. 错误标准化:统一的错误类型和处理

2.2 三层架构

┌─────────────────────────────────────────────────┐
│              应用层 (Application Layer)           │
│  ssh_exec() / ssh_exec_simple() / 便捷函数       │
├─────────────────────────────────────────────────┤
│              适配层 (Adapter Layer)               │
│  CrossPlatformCommandAdapter                      │
│  ┌─────────────┐ ┌─────────────┐ ┌────────────┐ │
│  │ Shell检测    │ │ 模式选择    │ │ 命令转译   │ │
│  └─────────────┘ └─────────────┘ └────────────┘ │
│  ┌─────────────┐ ┌─────────────┐ ┌────────────┐ │
│  │ 脚本生成    │ │ 执行引擎    │ │ 结果标准化 │ │
│  └─────────────┘ └─────────────┘ └────────────┘ │
├─────────────────────────────────────────────────┤
│              传输层 (Transport Layer)             │
│  SSH / SCP / 本地Shell                           │
└─────────────────────────────────────────────────┘

2.3 三种执行模式

模式适用场景可靠性性能
DIRECT(直接执行)简单命令(无特殊字符)⭐⭐⭐⭐⭐⭐⭐⭐
INLINE_ESCAPED(内联转译)中等复杂度命令⭐⭐⭐⭐⭐⭐⭐⭐
SCRIPT_FILE(脚本文件)复杂命令(推荐)⭐⭐⭐⭐⭐⭐⭐⭐

自动选择逻辑:

命令复杂度判断:
├─ 命令长度 > 500字符 → SCRIPT_FILE
├─ 包含循环/条件/函数 → SCRIPT_FILE
├─ 包含awk/sed/perl/python -c → SCRIPT_FILE
├─ 包含多层引号嵌套 → SCRIPT_FILE
├─ 包含管道+重定向组合 → SCRIPT_FILE
└─ 其他 → INLINE_ESCAPED 或 DIRECT

三、核心机制详解

3.1 Shell环境自动检测

def _detect_shell(self) -> ShellType:
    if os.name == 'nt':
        if os.environ.get('PSModulePath'):
            return ShellType.POWERSHELL
        return ShellType.CMD
    shell = os.environ.get('SHELL', '/bin/sh').lower()
    if 'bash' in shell: return ShellType.BASH
    elif 'zsh' in shell: return ShellType.ZSH
    return ShellType.SH

3.2 脚本文件方式(最可靠)

执行流程:

  1. 创建临时脚本文件(含shebang和set -e)
  2. SCP上传到远程服务器 /tmp/ 目录
  3. SSH执行脚本
  4. 清理远程和本地临时文件
  5. 返回标准化结果

优势:

3.3 内联转译方式

核心策略:

  1. 将命令中的单引号转义为 '\''(Bash单引号转义)
  2. 用单引号包裹整个命令作为SSH参数
  3. PowerShell中单引号内的内容不进行变量展开

转义规则:

原始命令: echo 'Hello World' && date
转义后:   'echo '\''Hello World'\'' && date'

3.4 结果标准化

@dataclass
class CommandResult:
    success: bool           # 是否成功
    returncode: int         # 返回码
    stdout: str             # 标准输出
    stderr: str             # 标准错误
    command: str            # 原始命令
    mode: CommandMode       # 执行模式
    shell_type: ShellType   # Shell类型
    duration_ms: float      # 耗时(毫秒)
    error_type: str         # 错误类型
    error_message: str      # 错误信息
    metadata: dict          # 元数据

四、使用指南

4.1 快速开始

from cross_platform_command_adapter import ssh_exec, ssh_exec_simple

# 方式1:便捷函数(推荐)
success, stdout, stderr = ssh_exec_simple('huodou-cloud', 'hostname')

# 方式2:完整结果
result = ssh_exec('huodou-cloud', 'systemctl status nginx')
if result.success:
    print(result.stdout)
else:
    print(f"失败: {result.error_message}")

# 方式3:复杂命令(自动使用脚本文件方式)
complex_cmd = """
for svc in zongyuan-memory-gateway zongyuan-context-assembler; do
    echo "=== $svc ==="
    systemctl is-active $svc
done
"""
result = ssh_exec('huodou-cloud', complex_cmd)

4.2 最佳实践

✅ 推荐做法

  1. 复杂命令使用脚本文件方式 ``python # 适配器会自动选择脚本文件方式 result = ssh_exec('host', 'for i in ...; do ...; done') ``
  1. 简单命令直接执行 ``python result = ssh_exec('host', 'uptime') ``
  1. 使用便捷函数处理简单场景 ``python success, stdout, stderr = ssh_exec_simple('host', 'df -h') ``
  1. 检查返回结果 ``python if not result.success: logger.error(f"命令失败: {result.error_message}") ``

❌ 避免做法

  1. 不要手动拼接复杂的SSH命令 ```python # 错误:手动拼接,容易出错 cmd = f"ssh host '{complex_command}'" subprocess.run(cmd, shell=True)

# 正确:使用适配器 result = ssh_exec('host', complex_command) ```

  1. 不要在PowerShell中使用双引号包裹SSH命令 ```powershell # 错误:双引号内的$会被PowerShell展开 ssh host "echo $HOME"

# 正确:使用适配器自动处理 ```

  1. 不要忽略错误处理 ```python # 错误:忽略返回码 ssh_exec('host', 'risky_command')

# 正确:检查结果 result = ssh_exec('host', 'risky_command') if not result.success: handle_error(result) ```

4.3 常见问题排查

问题可能原因解决方案
命令语法错误PowerShell提前解析了特殊字符使用脚本文件方式
变量未展开单引号阻止了Bash变量展开检查命令是否需要变量展开
权限拒绝脚本文件未设置执行权限适配器自动设置chmod +x
超时命令执行时间过长增加timeout参数
SCP上传失败网络问题或SSH配置错误检查SSH连接和配置

五、集成方案

5.1 集成到现有运维脚本

#!/usr/bin/env python3
"""
运维脚本示例:使用跨平台命令执行适配器
"""
import sys
sys.path.insert(0, '/path/to/scripts')
from cross_platform_command_adapter import ssh_exec, CrossPlatformCommandAdapter

# 初始化适配器(开启调试模式)
adapter = CrossPlatformCommandAdapter(debug=True)

# 批量执行命令
commands = [
    'systemctl --failed --no-legend',
    'free -h',
    'df -h /',
]

for cmd in commands:
    result = adapter.execute_remote('huodou-cloud', cmd)
    if result.success:
        print(f"✅ {cmd}")
        print(result.stdout)
    else:
        print(f"❌ {cmd}: {result.error_message}")

# 导出执行日志
adapter.export_log('/var/log/zongyuan/command_execution_log.json')

5.2 集成到Ansible/自动化工具

# Ansible playbook 示例
- name: 执行远程命令
  hosts: all
  tasks:
    - name: 使用适配器执行复杂命令
      command: python3 /opt/scripts/cross_platform_command_adapter.py --host {{ inventory_hostname }} --command "{{ complex_command }}"
      register: result
      
    - name: 检查结果
      assert:
        that: result.rc == 0
        fail_msg: "命令执行失败"

5.3 与记忆网关集成

# 将执行结果上报到记忆网关
def execute_and_report(ssh_host, command, gateway_url='http://127.0.0.1:9120'):
    result = ssh_exec(ssh_host, command)
    
    # 上报到记忆网关
    truth_data = {
        'key': f'command_execution.{ssh_host}.{hash(command)}',
        'value': {
            'command': command,
            'success': result.success,
            'duration_ms': result.duration_ms,
            'mode': result.mode.value,
        },
        'category': 'execution_log',
    }
    requests.post(f'{gateway_url}/api/truth/upsert', json=truth_data)
    
    return result

六、性能与可靠性

6.1 性能对比

执行模式简单命令复杂命令可靠性
直接SSH(手动)~50ms经常失败低
INLINE_ESCAPED~60ms~80ms中高
SCRIPT_FILE~200ms~250ms极高

结论: 脚本文件方式虽然增加了约150ms的开销(SCP上传),但可靠性大幅提升,是复杂命令的首选。

6.2 可靠性保障

  1. 临时文件自动清理:执行完成后自动删除本地和远程临时文件
  2. 超时控制:支持自定义超时时间,防止命令挂起
  3. 错误捕获:完整捕获异常,标准化错误类型
  4. 执行日志:记录所有执行历史,支持审计和回溯
  5. 幂等性:相同命令重复执行结果一致

七、扩展与未来规划

7.1 已支持

7.2 规划中

7.3 长期愿景

构建统一的跨平台命令执行框架,成为ZONGYUAN-ROOT自治体系的基础设施层,支撑:


八、总结

核心价值

  1. 彻底解决 PowerShell ↔ Bash 转译冲突问题
  2. 自动选择 最优执行模式,无需人工判断
  3. 统一API 屏蔽底层差异,简化开发
  4. 高可靠性 脚本文件方式确保复杂命令正确执行
  5. 可观测性 完整的执行日志和统计

一句话总结

"复杂命令用脚本,简单命令直接跑,跨平台转译不再是烦恼。"


Ω₀⊂⊙∞⊂Ω | DID-BR-000002 | ZONGYUAN-ROOT | 跨平台命令执行适配器 V1.0 | 永久锁档

规则即本体 · 真值即记忆 · 实例即载体
Ω₀⊂⊙∞⊂Ω | DID-BR-000002 | 元极恒一 · 超认知永恒自治