convez.ai
MCP ServerDevOps & InfraestruturaAvançado
yuigahamaaa

SSH Tool para Agentes IA

yuigahamaaa/ai-ssh-tool

SSH remoto com multi-hop, MCP, agendamento e visibilidade cross-agent

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP que oferece execução remota via SSH com suporte a multi-hop, transferência de arquivos, execução em background e agendamento compartilhado de tarefas. Projetado especificamente para agentes de IA (Claude, Cursor, Copilot) trabalharem em servidores remotos através de bastions corporativos.

Instalação

$npx convez-ai yuigahamaaa/ai-ssh-tool

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
1
Acompanhando
0
Saúde
28%
Último commit
há 1 mês
Versão
—
Issues abertas
2
Contribuidores
3

Casos de uso

  • Agentes IA executando tarefas em infraestrutura remota através de bastions
  • Pipelines de deploy e CI/CD controlados por agentes
  • Transferência automática de arquivos e pastas entre agentes e servidores
  • Execução paralela de comandos com fila de tarefas pesadas serializada

Veredito

Ferramenta robusta e bem arquitetada para agentes IA operarem em ambientes corporativos complexos. Resolve problemas reais de jump hosts múltiplos, persistência de conexão e visibilidade cross-agent, com segurança baseada em chaves SSH e timeout automático.

README

A tradução para o português deste README ainda está na fila.

ssh-tool

SSH tool designed for AI agents — multi-hop jump hosts, MCP server, file/folder transfer, shared VM scheduler, background execution, and cross-agent task visibility.

Node.js License: MIT Tests

English | 中文


English

Why

AI coding agents (Claude, Cursor, Copilot, etc.) need to work on remote servers through SSH. Existing tools like node-ssh or raw ssh2 are library-level — they don't provide:

  • Multi-hop jump host chains (corporate bastion → internal network)
  • Persistent connection reuse (avoid repeated handshakes)
  • MCP protocol integration for native AI tool calling
  • Folder transfer with automatic compression
  • Background command execution with status polling
  • Shared VM scheduler for multiple AI sessions
  • Default serial execution for tests, builds, installs, and scripts
  • Cross-agent task visibility and queue status
  • Large output capture with file-backed logs
  • Automatic command timeout termination

ai-ssh-tool fills this gap. A complete SSH remote execution platform designed from the ground up for AI agents.

Features

FeatureDescription
N-hop jump hostsDeclarative JSON config, connect through any number of bastions
Daemon modeBackground process keeps connections alive, commands execute instantly
MCP ServerStandard Model Context Protocol — 31 tools for AI agents
File streamingUpload/download large files without loading into memory
Folder transferCompress → transfer → decompress, fully automated
Shared schedulerssh_exec and ssh_exec_background route through daemon scheduler
Default heavy-task serializationTests, builds, installs, and scripts queue behind other heavy work
Cross-agent task visibilityRunning, queued, and recent tasks are visible to other AI sessions
Large output filesReturned output is bounded; full stdout/stderr are saved to scheduler output files
Host load monitoringGet CPU, memory, process count, and scheduler state
Auto timeout terminationAutomatically kill remote commands on timeout
Atomic scheduler stateQueued/running task state is persisted safely
Smart cleanupAutomatic old output cleanup to prevent garbage buildup
SSH ConfigAuto-parse ~/.ssh/config with ProxyJump support
Profile managementSave and reuse connection configs
Cross-platformWindows (named pipes) + Unix (socket)
Debug loggingPer-session log files for troubleshooting

🔐 Security Best Practices (IMPORTANT!)

Always use SSH keys instead of passwords in production!

✅ Recommended: SSH Key Authentication (Most Secure)

{
  "target": {
    "host": "192.168.1.100",
    "username": "root",
    "privateKey": "-----BEGIN OPENSSH PRIVATE KEY-----\n...your private key content...\n-----END OPENSSH PRIVATE KEY-----"
  }
}

⚠️ Password Usage (For testing only!)

{
  "target": {
    "host": "192.168.1.100",
    "username": "root",
    "password": "your-password"
  }
}

⚠️ Critical Warnings:

  • NEVER commit config files with passwords to Git!
  • Add your config files to .gitignore!
  • ProfileManager uses XOR obfuscation (NOT encryption) for stored passwords - it only prevents casual viewing
  • Always use SSH keys in production!

🛡️ Security Measures

MeasureDescription
File permissionsprofiles.json has 600 permissions (owner-only read)
Directory permissions~/.opencode/ssh/ has 700 permissions (owner-only access)
Password obfuscationXOR obfuscation (NOT encryption, just prevents casual viewing)
Task file permissionsTask JSON files have 600 permissions

Quick Start

# Install
git clone https://github.com/yuigahamaaa/ai-ssh-tool.git
cd ai-ssh-tool
npm install
npm run build

# Create config
echo '{"target":{"host":"192.168.1.100","username":"root","password":"your-password"}}' > my-server.json

# Execute command
node dist/cli/ssh-exec.js --config my-server.json --command "uname -a"

🎯 Key New Features

1. Shared VM Scheduler

ssh_exec now uses the daemon scheduler by default. Heavy commands such as tests, builds, installs, and scripts are serialized per host so multiple AI sessions do not accidentally compete for the same VM.

{
  "name": "ssh_exec",
  "parameters": {
    "command": "npm test",
    "intent": "test",
    "cost": "large",
    "reason": "Verify changes before reporting."
  }
}

If the VM is busy, the command may be queued:

{
  "ok": true,
  "kind": "schedule_decision",
  "action": "queued",
  "taskId": "t_xxx",
  "queuePosition": 1,
  "data": {
    "action": "queued",
    "taskId": "t_xxx",
    "queuePosition": 1,
    "recommendedNextStep": "Do unrelated read-only work; call ssh_wait_task or ssh_queue_status later."
  },
  "agentGuidance": [
    "Task was queued. Do not immediately resubmit the same command..."
  ],
  "recommendedNextStep": "Do unrelated read-only work; call ssh_wait_task or ssh_queue_status later."
}

Scheduler-related MCP tools return a uniform JSON envelope: ok, kind, data, and agentGuidance. ssh_exec and ssh_schedule also keep action, taskId, and result at the top level for backward compatibility.

2. Cross-Agent Task Visibility

Scheduler state is persisted under ~/.ssh-tool/scheduler/, so multiple MCP sessions can see what is running, what is queued, and what recently completed. Use ssh_queue_status, ssh_wait_task, and ssh_exec_status instead of rerunning queued or timed-out commands.

3. Large Output Handling

Foreground output is bounded to protect the AI context. Full stdout/stderr are written to internal output files and returned as metadata:

{
  "result": {
    "truncated": true,
    "stdoutBytes": 98304,
    "stderrBytes": 2048,
    "stdoutPath": "~/.ssh-tool/scheduler/outputs/t_xxx.stdout",
    "stderrPath": "~/.ssh-tool/scheduler/outputs/t_xxx.stderr"
  }
}

4. Virtual Working Directory

ssh_cd sets a per-agent, per-host virtual cwd. It is not a persistent remote shell cd; it only stores cwd metadata that later ssh_exec and ssh_schedule calls use when cwd is omitted. It does not affect other AI sessions or shared SSH sessions.

5. Automatic Timeout Termination

When a command times out:

  1. We first send TERM signal for graceful termination
  2. Wait 100ms for cleanup
  3. Send KILL if still running
  4. Clean up resources
// auto-kill on timeout
const result = await remoteExec(client, command, { timeout: 30000 });

Usage Modes

1. CLI — Scheduler-Aware Execution

Non-interactive CLI commands use the daemon scheduler by default. Use --scheduler bypass only as an explicit escape hatch.

# Single command
node dist/cli/ssh-exec.js --config server.json --command "df -h"

# Inline JSON config
node dist/cli/ssh-exec.js --config-json '{"target":{"host":"10.0.0.1","username":"root"}}' --command "uptime"

# Use saved profile name
node dist/cli/ssh-exec.js --profile-name my-server --command "uptime"

# Use inline profile JSON
node dist/cli/ssh-exec.js --profile-json '{"name":"my-server","chain":[{"name":"target","host":"10.0.0.1","port":22,"auth":{"username":"root","password":"pass"}}]}' --command "uptime"

# Interactive shell
node dist/cli/ssh-exec.js --config server.json --shell
node dist/cli/ssh-exec.js --profile-name my-server --shell

2. Daemon — Persistent Connections (Recommended)

# First call auto-starts daemon, subsequent calls reuse connection
node dist/cli/ssh-exec.js daemon exec --config server.json --command "free -h"
node dist/cli/ssh-exec.js daemon exec --config server.json --command "docker ps"

# Or use profile
node dist/cli/ssh-exec.js daemon exec --profile-name my-server --command "free -h"

# Manage sessions
node dist/cli/ssh-exec.js daemon sessions
node dist/cli/ssh-exec.js daemon stop

3. MCP Server — AI Agent Integration (Recommended)

# Start MCP server (stdio mode)
node dist/mcp-server.js --config server.json

# Or via CLI
node dist/cli/ssh-exec.js mcp --config server.json

Claude Desktop / Cursor / OpenCode config:

Claude Desktop / Cursor:

{
  "mcpServers": {
    "ssh-remote": {
      "command": "node",
      "args": ["/path/to/ai-ssh-tool/dist/mcp-server.js", "--config", "/path/to/server.json"]
    }
  }
}

OpenCode:

{
  "mcpServers": {
    "ssh-remote": {
      "command": "node",
      "args": ["/path/to/ai-ssh-tool/dist/mcp-server.js", "--config", "/path/to/server.json"]
    }
  }
}

4. File & Folder Transfer

The unified upload and download actions auto-detect whether the path is a file or a folder — no need to choose a separate command for each.

# Upload a file or folder (auto-detected)
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action upload --local ./app.tar.gz --remote /tmp/app.tar.gz
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action upload --local ./my-project --remote /opt/my-project

# Download a file or folder (auto-detected)
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action download --remote /var/log/syslog --local ./syslog.txt
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action download --remote /opt/my-project --local ./downloaded

5. Background Execution (Detach)

# Start a long-running command in background
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub start --command "nohup python train.py > train.log 2>&1 &"

# Check status
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub status --task-id <taskId>

# Read output
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub output --task-id <taskId>

# Cancel
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub cancel --task-id <taskId>

MCP Tools (21 total)

CategoryToolDescription
Executionssh_execRun shell command on remote server
File Readssh_read_fileRead file content
File Writessh_write_fileWrite content to file
Directoryssh_list_dirList directory contents
Checkssh_existsCheck if path exists
Statsssh_statGet file/dir stats
Searchssh_grepSearch patterns in files
Findssh_findFind files by name/type
Uploadssh_uploadUpload file or folder (auto-detect: file→SFTP, folder→tar+gzip)
Downloadssh_downloadDownload file or folder (auto-detect: file→SFTP, folder→tar+gzip)
Backgroundssh_exec_backgroundStart detached command
Statusssh_exec_statusGet background task status and output
Cancelssh_exec_cancelCancel running task
List Tasksssh_list_tasksList all tasks (exec + background, cross-process visible)
Host Loadssh_get_host_loadGet remote host load plus scheduler state
Port Forwardssh_local_forwardLocal port forwarding (local:port -> remote:port
Remote Forwardssh_remote_forwardRemote port forwarding (remote:port -> local:port
Stop Forwardssh_stop_forwardStop port forwarding by id
List Forwardsssh_list_forwardsList active port forwards
Virtual cwdssh_cdSet this AI session's virtual cwd; not a persistent remote shell cd
Profilesssh_list_profilesList saved connection profiles
Sessionsssh_list_sessionsList active SSH sessions
Disconnectssh_disconnectDisconnect a session

Configuration

Direct connection:

{
  "target": { "host": "10.0.0.1", "port": 22, "username": "root", "password": "xxx" }
}

Via jump hosts:

{
  "gateways": [
    { "host": "bastion.corp.com", "username": "ops", "password": "xxx" },
    { "host": "internal-gw.local", "username": "admin", "password": "yyy" }
  ],
  "target": { "host": "10.3.3.3", "username": "root", "password": "zzz" }
}
FieldRequiredDefaultDescription
target.hostYes—Server hostname/IP
target.usernameYes—SSH username
target.passwordNo—Password (or use privateKey)
target.portNo22SSH port
target.privateKeyNo—Private key content
gatewaysNo[]Jump host chain
timeoutNo30000Connection timeout (ms)

Command Reference

CommandDescription
--config <file>SSH config file path
--config-json '<JSON>'Inline JSON config
--profile-name <name>Use saved profile name
--profile-json '<JSON>'Inline profile JSON
--command "<cmd>"Command to execute
--shellInteractive shell
--debugEnable debug logging
daemon startStart daemon
daemon stopStop daemon
daemon execExecute via daemon
daemon sessionsList active sessions
daemon disconnect <id>Disconnect session
daemon pingCheck daemon status
daemon transferFile/folder transfer
daemon bg-execBackground execution
mcpStart MCP server

Testing

npm run test:ci

CI runs the stable fast suite: 211 tests across profile, logging, session, daemon IPC, scheduler, output store, virtual cwd, and scheduler IPC modules.

Extended suites are available manually:

npm run test:transfer
npm run test:ssh
npm run test:integration
npm run test:performance

Debugging

node dist/cli/ssh-exec.js --debug --config server.json --command "ls"
# Generates: logs/debug-192.168.1.100-ls-20260531-021557.log
Log KeywordIssueFix
All configured authentication methods failedAuth failureCheck username/password
getaddrinfo ENOTFOUNDDNS failureCheck IP address
Timed out while waiting for handshakeConnection timeoutCheck network/firewall
ENOENT .ssh-exec-daemon.sockDaemon not runningdaemon start

Project Structure

src/
├── connection.ts        # SSH connection chain (N-hop)
├── session-manager.ts   # Multi-session management
├── gateway.ts           # Main facade
├── daemon.ts            # Background daemon process
├── daemon-client.ts     # IPC client for daemon
├── ipc-protocol.ts      # IPC message framing
├── mcp-server.ts        # MCP protocol server
├── file-transfer.ts     # File/folder transfer (streaming)
├── scheduler/           # Shared scheduler (default exec path)
├── background-exec.ts   # Legacy detached execution wrapper
├── exec-task-manager.ts # Legacy local task store for compatibility
├── remote-fs.ts         # SFTP file operations
├── remote-shell.ts      # Remote command execution
├── remote-tools.ts      # Tool definitions for AI
├── profile-manager.ts   # Connection profile storage
├── ssh-config.ts        # ~/.ssh/config parser
├── logger.ts            # Debug logging
├── check-deps.ts        # Dependency checker
├── types.ts             # TypeScript type definitions
└── cli/
    ├── ssh-exec.ts      # CLI entry point
    └── daemon-commands.ts

Comparison

CapabilityThis ToolRaw SSHnode-sshVS Code Remote
N-hop jump hostsJSON declarativeProxyJumpjumpHostAuto
Connection reuseDaemon autoManualNot supportedAuto
AI tool integration21 MCP toolsNoneNoneCopilot
Folder transferAuto compressNeeds scpNoneBuilt-in
Background execDetach modescreen/tmuxNoneNone
Unified task tracking✅ All tasks❌❌❌
Cross-process visibility✅❌❌❌
Host load monitoring✅❌❌❌
Auto timeout termination✅❌❌❌
RuntimeNode.jsSystemNode.jsVS Code

License

MIT


中文

为什么需要这个工具

AI 编程助手(Claude、Cursor、Copilot 等)需要通过 SSH 操作远程服务器。现有的 node-ssh 或原生 ssh2 只是库级别的封装,缺少:

  • 多级跳板机链路(公司堡垒机 → 内网服务器)
  • 持久连接复用(避免重复握手)
  • MCP 协议集成(AI 原生工具调用)
  • 文件夹自动压缩传输
  • 后台命令执行 + 状态轮询
  • 多 AI 会话共享 VM 调度器
  • 测试、构建、安装、脚本默认串行
  • 跨 Agent 任务可见性和队列状态
  • 大输出自动落盘,避免塞爆 AI 上下文
  • 命令超时自动终止

ai-ssh-tool 专为解决这些问题而生,是一个为 AI Agent 从零设计的完整 SSH 远程执行平台。

核心能力

能力说明
N 级跳板机JSON 声明式配置,支持任意级跳转
Daemon 持久化后台进程保持连接,命令秒级执行
MCP Server标准 MCP 协议,31 个工具供 AI 调用
流式文件传输大文件上传/下载,不占内存
文件夹传输压缩 → 传输 → 解压,全自动
共享调度器ssh_exec 和 ssh_exec_background 默认走 daemon scheduler
重任务默认串行测试、构建、安装、脚本会排队,避免多个 AI 抢 VM
跨 Agent 任务可见running、queued、recent 任务对其他 AI 会话可见
大输出落盘内联输出有界,完整 stdout/stderr 保存为调度器输出文件
主机负载监控获取 CPU、内存、进程数和 scheduler 状态
超时自动终止命令超时后自动终止远程进程
调度状态原子写入queued/running 任务状态安全持久化
智能清理自动清理旧输出,防止垃圾堆积
SSH Config自动解析 ~/.ssh/config,支持 ProxyJump
配置管理保存和复用连接配置
跨平台Windows(命名管道)+ Unix(Socket)
调试日志每个会话独立日志文件,便于排查

🔐 安全最佳实践(必读!)

生产环境请务必使用 SSH 密钥,不要使用密码!

✅ 推荐方式:SSH 密钥认证(最安全)

{
  "target": {
    "host": "192.168.1.100",
    "username": "root",
    "privateKey": "-----BEGIN OPENSSH PRIVATE KEY-----\n...你的私钥内容...\n-----END OPENSSH PRIVATE KEY-----"
  }
}

⚠️ 密码认证(仅用于测试环境!)

{
  "target": {
    "host": "192.168.1.100",
    "username": "root",
    "password": "你的密码"
  }
}

⚠️ 重要警告:

  • 永远不要把包含密码的配置文件提交到 Git!
  • 把你的配置文件添加到 .gitignore!
  • ProfileManager 使用 XOR 混淆(不是加密)存储密码 - 仅防止随手查看
  • 生产环境必须使用 SSH 密钥!

🛡️ 已有的安全措施

措施说明
文件权限profiles.json 权限为 600(仅所有者可读)
目录权限~/.opencode/ssh/ 权限为 700(仅所有者可访问)
密码混淆XOR 混淆(非加密,仅防随手看)
任务文件权限任务 JSON 文件权限为 600

🎯 新增核心功能

1. 共享 VM 调度器

ssh_exec 现在默认进入 daemon scheduler。测试、构建、安装、脚本等重任务会按 host 串行,避免多个 AI 会话同时抢同一台 VM。

{
  "name": "ssh_exec",
  "parameters": {
    "command": "npm test",
    "intent": "test",
    "cost": "large",
    "reason": "Verify changes before reporting."
  }
}

如果 VM 正忙,命令可能进入队列:

{
  "ok": true,
  "kind": "schedule_decision",
  "action": "queued",
  "taskId": "t_xxx",
  "queuePosition": 1,
  "data": {
    "action": "queued",
    "taskId": "t_xxx",
    "queuePosition": 1,
    "recommendedNextStep": "Do unrelated read-only work; call ssh_wait_task or ssh_queue_status later."
  },
  "agentGuidance": [
    "Task was queued. Do not immediately resubmit the same command..."
  ],
  "recommendedNextStep": "Do unrelated read-only work; call ssh_wait_task or ssh_queue_status later."
}

调度相关 MCP 工具统一返回 JSON envelope:ok、kind、data、agentGuidance。ssh_exec / ssh_schedule 为兼容旧提示词,仍会把 action、taskId、result 保留在顶层。

2. 跨 Agent 任务可见性

调度状态持久化在 ~/.ssh-tool/scheduler/ 下。多个 MCP 会话可以看到当前 running、queued、recent 任务。queued 或 wait timeout 后,应使用 ssh_queue_status、ssh_wait_task、ssh_exec_status 查询同一个 taskId,不要重复提交命令。

3. 大输出处理

前台返回的 stdout/stderr 是有界 tail,避免占满 AI 上下文。完整输出会落盘并在结果里返回路径:

{
  "result": {
    "truncated": true,
    "stdoutBytes": 98304,
    "stderrBytes": 2048,
    "stdoutPath": "~/.ssh-tool/scheduler/outputs/t_xxx.stdout",
    "stderrPath": "~/.ssh-tool/scheduler/outputs/t_xxx.stderr"
  }
}

4. 虚拟工作目录

ssh_cd 设置当前 AI 会话在某个 host 上的虚拟 cwd。它不是远端 shell 的持久 cd,只是保存 cwd 元数据;后续 ssh_exec / ssh_schedule 没显式传 cwd 时会使用它。它不影响其他 AI 或共享 SSH 会话。

5. 超时自动终止

当命令超时时:

  1. 首先发送 TERM 信号让进程优雅终止
  2. 等待 100ms 让进程清理
  3. 如果还在运行,发送 KILL 强制终止
  4. 清理所有资源
// 超时自动终止
const result = await remoteExec(client, command, { timeout: 30000 });

快速开始

# 安装
git clone https://github.com/yuigahamaaa/ai-ssh-tool.git
cd ai-ssh-tool
npm install
npm run build

# 创建配置
echo '{"target":{"host":"192.168.1.100","username":"root","password":"你的密码"}}' > my-server.json

# 执行命令
node dist/cli/ssh-exec.js --config my-server.json --command "uname -a"

使用方式

1. CLI 调度感知执行

非交互式 CLI 命令默认走 daemon scheduler。只有明确需要逃生通道时才使用 --scheduler bypass。

# 执行单条命令
node dist/cli/ssh-exec.js --config server.json --command "df -h"

# 直接传 JSON(不需要配置文件)
node dist/cli/ssh-exec.js --config-json '{"target":{"host":"10.0.0.1","username":"root"}}' --command "uptime"

# 使用保存的配置
node dist/cli/ssh-exec.js --profile-name my-server --command "uptime"

# 使用直接传 profile JSON
node dist/cli/ssh-exec.js --profile-json '{"name":"my-server","chain":[{"name":"target","host":"10.0.0.1","port":22,"auth":{"username":"root","password":"pass"}}]}' --command "uptime"

# 交互式 shell
node dist/cli/ssh-exec.js --config server.json --shell
node dist/cli/ssh-exec.js --profile-name my-server --shell

2. Daemon 持久化模式(推荐)

# 首次自动启动 daemon,后续复用连接,无需重复握手
node dist/cli/ssh-exec.js daemon exec --config server.json --command "free -h"
node dist/cli/ssh-exec.js daemon exec --config server.json --command "docker ps"

# 管理会话
node dist/cli/ssh-exec.js daemon sessions
node dist/cli/ssh-exec.js daemon stop

3. MCP Server — AI Agent 集成(推荐)

# 启动 MCP 服务器(stdio 模式)
node dist/mcp-server.js --config server.json

# 或通过 CLI 启动
node dist/cli/ssh-exec.js mcp --config server.json

Claude Desktop / Cursor / OpenCode 配置示例:

Claude Desktop / Cursor:

{
  "mcpServers": {
    "ssh-remote": {
      "command": "node",
      "args": ["/path/to/ai-ssh-tool/dist/mcp-server.js", "--config", "/path/to/server.json"]
    }
  }
}

OpenCode:

{
  "mcpServers": {
    "ssh-remote": {
      "command": "node",
      "args": ["/path/to/ai-ssh-tool/dist/mcp-server.js", "--config", "/path/to/server.json"]
    }
  }
}

4. 文件 / 文件夹传输

upload 和 download 自动判断路径是文件还是文件夹,无需再选子命令。

# 上传文件 / 文件夹(自动判断)
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action upload --local ./app.tar.gz --remote /tmp/app.tar.gz
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action upload --local ./my-project --remote /opt/my-project

# 下载文件 / 文件夹(自动判断)
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action download --remote /var/log/syslog --local ./syslog.txt
node dist/cli/ssh-exec.js daemon transfer --config server.json \
  --action download --remote /opt/my-project --local ./downloaded

5. 后台执行(detach 模式)

# 启动后台命令,立即返回 task handle
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub start --command "nohup python train.py > train.log 2>&1 &"

# 查询任务状态
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub status --task-id <taskId>

# 读取输出日志
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub output --task-id <taskId>

# 取消任务
node dist/cli/ssh-exec.js daemon bg-exec --config server.json \
  --sub cancel --task-id <taskId>

MCP 核心工具列表(共 31 个,下面列常用入口)

类别工具名说明
执行ssh_exec在远程服务器执行 shell 命令
读文件ssh_read_file读取远程文件内容
写文件ssh_write_file写入远程文件
目录ssh_list_dir列出目录内容
检查ssh_exists检查路径是否存在
信息ssh_stat获取文件/目录 stat 信息
搜索ssh_grep在远程文件中搜索正则
查找ssh_find按名称/类型查找文件
上传ssh_upload上传文件 / 文件夹(自动判断:文件→SFTP,目录→tar+gzip)
下载ssh_download下载文件 / 文件夹(自动判断:文件→SFTP,目录→tar+gzip)
后台ssh_exec_background启动后台命令
状态ssh_exec_status查询后台任务状态和输出
取消ssh_exec_cancel取消运行中的任务
任务列表ssh_list_tasks列出所有任务(exec + background,跨进程可见)
主机负载ssh_get_host_load获取远程主机负载和 scheduler 状态
端口转发ssh_local_forward本地端口转发(本地端口 → 远程端口)
远程转发ssh_remote_forward远程端口转发(远程端口 → 本地端口)
停止转发ssh_stop_forward按 id 停止端口转发
转发列表ssh_list_forwards列出活跃的端口转发
虚拟 cwdssh_cd设置当前 AI 会话的虚拟 cwd;不是远端 shell 的持久 cd
配置列表ssh_list_profiles列出保存的连接配置
会话列表ssh_list_sessions列出活跃的 SSH 会话
断开连接ssh_disconnect断开指定会话

配置说明

直连:

{
  "target": { "host": "10.0.0.1", "port": 22, "username": "root", "password": "xxx" }
}

通过跳板机:

{
  "gateways": [
    { "host": "bastion.corp.com", "username": "ops", "password": "xxx" },
    { "host": "internal-gw.local", "username": "admin", "password": "yyy" }
  ],
  "target": { "host": "10.3.3.3", "username": "root", "password": "zzz" }
}
字段必填默认值说明
target.host是—服务器地址
target.username是—登录用户名
target.password否—密码(和 privateKey 二选一)
target.port否22SSH 端口
target.privateKey否—私钥内容
gateways否[]跳板机列表
timeout否30000连接超时(毫秒)

命令速查

命令说明
--config <文件>配置文件路径
--config-json '<JSON>'直接传 JSON 配置
--profile-name <名称>使用保存的配置名称
--profile-json '<JSON>'直接传 profile JSON
--command "<命令>"要执行的命令
--shell交互式 shell
--debug调试日志
daemon start启动 daemon
daemon stop停止 daemon
daemon exec通过 daemon 执行命令
daemon sessions查看活跃会话
daemon disconnect <id>断开指定连接
daemon ping检查 daemon 状态
daemon transfer文件/文件夹传输
daemon bg-exec后台执行管理
mcp启动 MCP 服务器

测试

npm run test:ci

CI 默认运行稳定 fast 集合:211 个测试,覆盖 profile、logger、session、daemon IPC、scheduler、output store、virtual cwd、scheduler IPC 等模块。

扩展测试可手动运行:

npm run test:transfer
npm run test:ssh
npm run test:integration
npm run test:performance

调试

node dist/cli/ssh-exec.js --debug --config server.json --command "ls"
# 生成日志: logs/debug-192.168.1.100-ls-20260531-021557.log
日志关键字问题处理
All configured authentication methods failed认证失败检查用户名/密码
getaddrinfo ENOTFOUNDDNS 解析失败检查 IP 地址
Timed out while waiting for handshake连接超时检查网络/防火墙
ENOENT .ssh-exec-daemon.sockDaemon 未启动执行 daemon start

项目结构

src/
├── connection.ts        # SSH 连接链(N 级跳转)
├── session-manager.ts   # 多会话管理
├── gateway.ts           # 主门面
├── daemon.ts            # 后台守护进程
├── daemon-client.ts     # IPC 客户端
├── ipc-protocol.ts      # IPC 消息协议
├── mcp-server.ts        # MCP 协议服务器
├── file-transfer.ts     # 文件/文件夹传输(流式)
├── scheduler/           # 共享调度器(默认执行路径)
├── background-exec.ts   # legacy 后台执行包装器
├── exec-task-manager.ts # legacy 本地任务存储(兼容旧后台执行)
├── remote-fs.ts         # SFTP 文件操作
├── remote-shell.ts      # 远程命令执行
├── remote-tools.ts      # AI 工具定义
├── profile-manager.ts   # 连接配置管理
├── ssh-config.ts        # ~/.ssh/config 解析
├── logger.ts            # 调试日志
├── check-deps.ts        # 依赖检查
├── types.ts             # TypeScript 类型定义
└── cli/
    ├── ssh-exec.ts      # CLI 入口
    └── daemon-commands.ts

与其他方案对比

能力本工具原生 SSHnode-sshVS Code Remote
N 级跳板机JSON 声明式ProxyJumpjumpHost自动
连接复用Daemon 自动手动不支持自动
AI 工具集成31 个 MCP 工具无无Copilot
文件夹传输自动压缩需 scp无内置
后台执行detach 模式screen/tmux无无
统一任务追踪✅ 所有任务❌❌❌
跨进程可见性✅❌❌❌
主机负载监控✅❌❌❌
超时自动终止✅❌❌❌
运行时Node.js系统自带Node.jsVS Code

许可证

MIT

Ver o original no GitHub

Bom para

Relacionados