Files
2026-11-18 01:10:51 +08:00

101 lines
3.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { expandHome } from './config.js'
const ANSI = /\u001b\[[0-9;?]*[a-zA-Z]/g
const MAX_OUTPUT = 24000
export function clean(text) {
return String(text || '').replace(ANSI, '').replace(/\r\n/g, '\n')
}
export function clip(text, limit = MAX_OUTPUT) {
const s = clean(text).replace(/\s+$/, '')
if (s.length <= limit) return s
return `${s.slice(0, limit)}\n…(输出太长,已截断,原长 ${s.length} 字符)`
}
/**
* 在远端执行一条命令。整个过程不交互:BatchMode 关掉一切密码提示,
* 首次连接自动记录 host key,连不上 10 秒就放弃。
*/
export function execRemote(server, command, { timeoutMs = 60000, stdin = null } = {}) {
const key = expandHome(server.key)
if (key && !existsSync(key)) {
return Promise.resolve({
ok: false,
code: null,
stdout: '',
stderr: `私钥不存在:${key}`,
ms: 0
})
}
const args = []
if (key) args.push('-i', key)
args.push(
'-p', String(server.port || 22),
'-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', 'ConnectTimeout=10',
'-o', 'ServerAliveInterval=15',
'-o', 'ServerAliveCountMax=3',
'-o', 'LogLevel=ERROR',
`${server.user}@${server.host}`,
'--',
command
)
const started = Date.now()
return new Promise((resolve) => {
let stdout = ''
let stderr = ''
let settled = false
const child = spawn('ssh', args, { stdio: ['pipe', 'pipe', 'pipe'] })
const finish = (result) => {
if (settled) return
settled = true
clearTimeout(timer)
resolve({
ok: result.code === 0,
code: result.code,
stdout: clip(stdout),
stderr: clip(stderr),
ms: Date.now() - started
})
}
const timer = setTimeout(() => {
try { child.kill('SIGKILL') } catch {}
finish({ code: 124 })
stderr += `\n超时:${Math.round(timeoutMs / 1000)} 秒没跑完,已中断。`
}, timeoutMs)
child.stdout.on('data', (b) => { if (stdout.length < MAX_OUTPUT * 2) stdout += b.toString('utf8') })
child.stderr.on('data', (b) => { if (stderr.length < MAX_OUTPUT * 2) stderr += b.toString('utf8') })
child.on('error', (error) => {
stderr += `\n启动 ssh 失败:${error.message}`
finish({ code: 127 })
})
child.on('close', (code) => finish({ code }))
if (stdin != null) {
child.stdin.end(stdin)
} else {
child.stdin.end()
}
})
}
/** 把一次执行结果整理成给人看的文本。 */
export function formatResult(server, command, result) {
const head = `$ ${server.user}@${server.host}: ${command}`
const foot = result.ok ? `(${result.ms} ms)` : `(退出码 ${result.code},${result.ms} ms)`
const parts = [head]
if (result.stdout) parts.push(result.stdout)
if (result.stderr) parts.push(result.ok ? `[stderr]\n${result.stderr}` : result.stderr)
if (!result.stdout && !result.stderr) parts.push('(没有输出)')
parts.push(foot)
return parts.join('\n')
}