@pyrokine/mcp-ssh 2.0.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,12 +3,46 @@
3
3
  *
4
4
  * ssh_connect, ssh_disconnect, ssh_list_sessions, ssh_reconnect, ssh_config_list
5
5
  */
6
+ import * as fs from 'fs';
7
+ import * as os from 'os';
8
+ import * as path from 'path';
6
9
  import { z } from 'zod';
7
10
  import { sessionManager } from '../session-manager.js';
8
11
  import { parseProxyJump, parseSSHConfig } from '../ssh-config.js';
9
- import { formatError, formatResult } from './utils.js';
12
+ import { expandTilde, formatError, formatResult } from './utils.js';
13
+ function loadTemplates() {
14
+ const fromEnv = process.env.SSH_MCP_TEMPLATES;
15
+ if (fromEnv) {
16
+ return JSON.parse(fromEnv);
17
+ }
18
+ const filePath = path.join(os.homedir(), '.mcp-ssh', 'templates.json');
19
+ if (!fs.existsSync(filePath)) {
20
+ return {};
21
+ }
22
+ return JSON.parse(fs.readFileSync(expandTilde(filePath), 'utf-8'));
23
+ }
24
+ function getTemplate(name) {
25
+ if (!name) {
26
+ return {};
27
+ }
28
+ const templates = loadTemplates();
29
+ const template = templates[name];
30
+ if (!template) {
31
+ const available = Object.keys(templates);
32
+ const suggestion = available.length
33
+ ? `Available templates: ${available.slice(0, 20).join(', ')}`
34
+ : 'No templates found. Define SSH_MCP_TEMPLATES or ~/.mcp-ssh/templates.json';
35
+ throw new Error(`Template '${name}' not found. ${suggestion}`);
36
+ }
37
+ return template;
38
+ }
39
+ function mergeEnv(templateEnv, argsEnv) {
40
+ const merged = { ...templateEnv, ...argsEnv };
41
+ return Object.keys(merged).length > 0 ? merged : undefined;
42
+ }
10
43
  // ========== Schemas ==========
11
44
  const connectSchema = z.object({
45
+ template: z.string().optional().describe('连接模板名,从 SSH_MCP_TEMPLATES 或 ~/.mcp-ssh/templates.json 读取'),
12
46
  configHost: z.string().optional().describe('使用 ~/.ssh/config 中的 Host 配置(推荐)'),
13
47
  configPath: z.string().optional().describe('SSH 配置文件路径(默认 ~/.ssh/config)'),
14
48
  host: z.string().optional().describe('服务器地址(使用 configHost 时可省略)'),
@@ -17,7 +51,9 @@ const connectSchema = z.object({
17
51
  keyPath: z.string().optional().describe('SSH 私钥路径'),
18
52
  port: z.number().optional().describe('SSH 端口,默认 22'),
19
53
  alias: z.string().optional().describe('连接别名(可选,默认使用 configHost 或 host)'),
20
- env: z.record(z.string()).optional().describe('环境变量'),
54
+ env: z.record(z.string(), z.string()).optional().describe('环境变量'),
55
+ defaultEnv: z.record(z.string(), z.string()).optional().describe('连接级默认环境变量'),
56
+ runAs: z.string().optional().describe('连接级默认执行用户,后续 ssh_exec 默认以该用户执行'),
21
57
  keepaliveInterval: z.number().optional().describe('心跳间隔(毫秒),默认 30000'),
22
58
  jumpHost: z
23
59
  .object({
@@ -43,17 +79,29 @@ const configListSchema = z.object({
43
79
  // ========== Handlers ==========
44
80
  async function handleConnect(args) {
45
81
  try {
46
- // 解析 configHost
47
- let host = args.host;
48
- let user = args.user;
49
- let port = args.port;
50
- let keyPath = args.keyPath;
82
+ const template = getTemplate(args.template);
83
+ const configHost = args.configHost ?? template.configHost;
84
+ let host = args.host ?? template.host;
85
+ let user = args.user ?? template.user ?? template.username;
86
+ let port = args.port ?? template.port;
87
+ let keyPath = args.keyPath ?? template.keyPath ?? template.privateKeyPath;
88
+ const password = args.password ?? template.password;
89
+ const requestedAlias = args.alias ?? template.alias ?? configHost;
90
+ const runAs = args.runAs ?? template.runAs;
91
+ const defaultEnv = mergeEnv(template.defaultEnv, args.defaultEnv);
92
+ const env = mergeEnv(template.env, args.env);
93
+ const keepaliveInterval = args.keepaliveInterval ?? template.keepaliveInterval;
51
94
  let jumpHostResolved;
52
- if (args.configHost) {
95
+ if (configHost) {
53
96
  const allHosts = parseSSHConfig(args.configPath);
54
- const hostConfig = allHosts.find((h) => h.host === args.configHost);
97
+ const hostConfig = allHosts.find((h) => h.host === configHost);
55
98
  if (!hostConfig) {
56
- return formatResult({ success: false, error: `Host '${args.configHost}' not found in SSH config` });
99
+ return formatResult({
100
+ success: false,
101
+ error: `Host '${configHost}' not found in SSH config`,
102
+ candidates: allHosts.map((item) => item.host).slice(0, 20),
103
+ suggestion: '调用 ssh_config_list 查看完整 Host 列表,或直接传 host/user/port',
104
+ });
57
105
  }
58
106
  // 显式参数优先于 config 值
59
107
  host = host || hostConfig.hostName || hostConfig.host;
@@ -68,19 +116,34 @@ async function handleConnect(args) {
68
116
  const jumpHostConfig = allHosts.find((h) => h.host === parsed.host);
69
117
  if (jumpHostConfig) {
70
118
  // 使用 config 中的配置,但 parsed 的 user/port 优先
119
+ const jumpUser = parsed.user || jumpHostConfig.user;
120
+ if (!jumpUser) {
121
+ return formatResult({
122
+ success: false,
123
+ error: `ProxyJump '${parsed.host}' is missing user`,
124
+ suggestion: '在 ProxyJump 中使用 user@host,或为跳板机 Host 配置 User',
125
+ });
126
+ }
71
127
  jumpHostResolved = {
72
128
  host: jumpHostConfig.hostName || jumpHostConfig.host,
73
129
  port: parsed.port || jumpHostConfig.port || 22,
74
- username: parsed.user || jumpHostConfig.user || 'root',
130
+ username: jumpUser,
75
131
  privateKeyPath: jumpHostConfig.identityFile,
76
132
  };
77
133
  }
78
134
  else {
79
135
  // 直接使用 parsed 的值
136
+ if (!parsed.user) {
137
+ return formatResult({
138
+ success: false,
139
+ error: `ProxyJump '${parsed.host}' is missing user`,
140
+ suggestion: '在 ProxyJump 中使用 user@host,或为跳板机 Host 配置 User',
141
+ });
142
+ }
80
143
  jumpHostResolved = {
81
144
  host: parsed.host,
82
145
  port: parsed.port || 22,
83
- username: parsed.user || 'root',
146
+ username: parsed.user,
84
147
  };
85
148
  }
86
149
  }
@@ -102,21 +165,44 @@ async function handleConnect(args) {
102
165
  privateKeyPath: args.jumpHost.keyPath,
103
166
  }
104
167
  : jumpHostResolved;
168
+ const finalPort = port || 22;
169
+ const finalAlias = requestedAlias || `${user}@${host}:${finalPort}`;
170
+ const identity = `${user}@${host}:${finalPort}`;
171
+ const sessionsBeforeConnect = sessionManager.listSessions();
172
+ const reused = sessionsBeforeConnect.some((session) => session.alias === finalAlias && session.connected);
173
+ const reusableSessions = sessionsBeforeConnect
174
+ .filter((session) => session.identity === identity && session.alias !== finalAlias && session.connected)
175
+ .map((session) => ({ alias: session.alias, runAs: session.runAs, connectedAt: session.connectedAt }));
105
176
  const alias = await sessionManager.connect({
106
177
  host,
107
- port: port || 22,
178
+ port: finalPort,
108
179
  username: user,
109
- password: args.password,
180
+ password,
110
181
  privateKeyPath: keyPath,
111
- alias: args.alias || args.configHost,
112
- env: args.env,
113
- keepaliveInterval: args.keepaliveInterval,
182
+ alias: requestedAlias,
183
+ template: args.template,
184
+ runAs,
185
+ defaultEnv,
186
+ env,
187
+ keepaliveInterval,
114
188
  jumpHost,
115
189
  });
116
190
  return formatResult({
117
191
  success: true,
118
192
  alias,
119
- message: `Connected to ${user}@${host}:${port || 22}${jumpHost ? ' via jump host' : ''}`,
193
+ reused,
194
+ identity,
195
+ loginUser: user,
196
+ runAs,
197
+ host,
198
+ port: finalPort,
199
+ defaultEnvKeys: defaultEnv ? Object.keys(defaultEnv) : [],
200
+ envKeys: env ? Object.keys(env) : [],
201
+ reusableSessions,
202
+ suggestion: reusableSessions.length > 0
203
+ ? '已有同 identity 的连接,可直接复用 reusableSessions 中的 alias'
204
+ : undefined,
205
+ message: `Connected to ${identity}${jumpHost ? ' via jump host' : ''}`,
120
206
  });
121
207
  }
122
208
  catch (error) {
@@ -180,15 +266,17 @@ async function handleConfigList(args) {
180
266
  // ========== Register ==========
181
267
  export function registerConnectionTools(server) {
182
268
  server.registerTool('ssh_connect', {
183
- description: `建立 SSH 连接并保持会话,支持密码、密钥认证,支持跳板机
184
-
185
- 可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息
186
- 支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)
187
-
188
- 示例:
189
- - 使用 ssh config: ssh_connect(configHost="myserver")
190
- - 密钥认证: ssh_connect(host="192.168.1.1", user="root", keyPath="/home/.ssh/id_rsa")
191
- - 跳板机: ssh_connect(host="内网IP", user="root", keyPath="...", jumpHost={host:"跳板机IP", user:"root", keyPath:"..."})`,
269
+ description: [
270
+ '建立 SSH 连接并保持会话,支持密码、密钥认证,支持跳板机',
271
+ '',
272
+ '可通过 configHost 参数使用 ~/.ssh/config 中的配置,无需重复填写连接信息',
273
+ '支持 Host 多别名、Host * 全局默认继承、ProxyJump(user@host:port 格式)',
274
+ '',
275
+ '示例',
276
+ '- 使用 ssh config,传入 configHost 为 "myserver"',
277
+ '- 密钥认证,传入 host、user、keyPath',
278
+ '- 跳板机,传入 host、user、keyPath 和 jumpHost 配置',
279
+ ].join('\n'),
192
280
  inputSchema: connectSchema,
193
281
  }, (args) => handleConnect(args));
194
282
  server.registerTool('ssh_disconnect', {
@@ -5,9 +5,18 @@
5
5
  * ssh_exec_batch, ssh_quick_exec, ssh_exec_parallel
6
6
  */
7
7
  import { z } from 'zod';
8
+ import * as fileOps from '../file-ops.js';
8
9
  import { sessionManager } from '../session-manager.js';
9
- import { formatError, formatResult } from './utils.js'; // ========== Schemas ==========
10
+ import { HARD_EXEC_MAX_OUTPUT_SIZE } from '../types.js';
11
+ import { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
10
12
  // ========== Schemas ==========
13
+ const maxOutputSizeSchema = z
14
+ .number()
15
+ .int()
16
+ .positive()
17
+ .max(HARD_EXEC_MAX_OUTPUT_SIZE)
18
+ .optional()
19
+ .describe('最大输出字符数,超过后截断并返回提示');
11
20
  const execSchema = z.object({
12
21
  alias: z.string().describe('连接别名'),
13
22
  command: z.string().describe('要执行的命令'),
@@ -16,14 +25,21 @@ const execSchema = z.object({
16
25
  .optional()
17
26
  .describe('超时(毫秒),默认 30000,长时间命令可设更大值如 600000(10 分钟),或用 ssh_pty_start 替代'),
18
27
  cwd: z.string().optional().describe('工作目录(可选)'),
19
- env: z.record(z.string()).optional().describe('额外环境变量'),
28
+ env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
20
29
  pty: z.boolean().optional().describe('是否使用 PTY 模式(用于 top 等交互式命令)'),
30
+ maxOutputSize: maxOutputSizeSchema,
31
+ runAs: z.string().optional().describe('本次命令使用的目标用户,覆盖连接级 runAs'),
32
+ useLoginUser: z.boolean().optional().describe('设为 true 时跳过连接级 runAs,直接以登录用户执行'),
33
+ loadProfile: z.boolean().optional().describe('runAs 执行时是否加载目标用户 shell 配置,默认 true'),
21
34
  });
22
35
  const execAsUserSchema = z.object({
23
36
  alias: z.string().describe('连接别名'),
24
37
  command: z.string().describe('要执行的命令'),
25
- targetUser: z.string().describe('目标用户名'),
38
+ targetUser: z.string().optional().describe('目标用户名,不传时使用连接级 runAs'),
26
39
  timeout: z.number().optional().describe('超时(毫秒)'),
40
+ cwd: z.string().optional().describe('工作目录(可选)'),
41
+ env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
42
+ maxOutputSize: maxOutputSizeSchema,
27
43
  loadProfile: z
28
44
  .boolean()
29
45
  .optional()
@@ -34,6 +50,7 @@ const execSudoSchema = z.object({
34
50
  command: z.string().describe('要执行的命令'),
35
51
  sudoPassword: z.string().optional().describe('sudo 密码(如果需要)'),
36
52
  timeout: z.number().optional().describe('超时(毫秒)'),
53
+ maxOutputSize: maxOutputSizeSchema,
37
54
  });
38
55
  const execBatchSchema = z.object({
39
56
  alias: z.string().describe('连接别名'),
@@ -55,7 +72,79 @@ const execParallelSchema = z.object({
55
72
  command: z.string().describe('要执行的命令'),
56
73
  timeout: z.number().optional().describe('每个命令的超时(毫秒),默认 30000'),
57
74
  });
58
- // ========== Handlers ==========
75
+ const execScriptSchema = z.object({
76
+ alias: z.string().describe('连接别名'),
77
+ script: z.string().describe('脚本内容'),
78
+ interpreter: z.string().optional().describe('解释器,默认 bash'),
79
+ targetUser: z.string().optional().describe('目标用户名,优先级高于 runAs'),
80
+ runAs: z.string().optional().describe('本次脚本使用的目标用户'),
81
+ cwd: z.string().optional().describe('工作目录(可选)'),
82
+ env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
83
+ timeout: z.number().optional().describe('超时(毫秒)'),
84
+ keepScript: z.boolean().optional().describe('是否保留远端临时脚本,默认 false'),
85
+ maxOutputSize: maxOutputSizeSchema,
86
+ });
87
+ function pushRisk(categories, signals, category, signal) {
88
+ categories.add(category);
89
+ signals.push(signal);
90
+ }
91
+ function classifyCommandRisk(command) {
92
+ const signals = [];
93
+ const categories = new Set();
94
+ const pipeCount = (command.match(/\|/g) ?? []).length;
95
+ const lowerCommand = command.toLowerCase();
96
+ if (command.length > 500) {
97
+ pushRisk(categories, signals, 'long-running', 'long_command');
98
+ }
99
+ if (/\bgrep\s+(?:-\S*R|--recursive)\b/.test(command)) {
100
+ pushRisk(categories, signals, 'long-running', 'recursive_grep');
101
+ }
102
+ if (/\bfind\b/.test(command) && !/\s-maxdepth\s+\d+/.test(command)) {
103
+ pushRisk(categories, signals, 'long-running', 'unbounded_find');
104
+ }
105
+ if (/\b(?:python|python3|node|perl|ruby)\b/.test(command)) {
106
+ pushRisk(categories, signals, 'script-execution', 'interpreter_script');
107
+ }
108
+ if (/\bsleep\s+\d{2,}\b/.test(command) || /\b(?:tail\s+-f|journalctl\s+-f|watch|top|htop)\b/.test(command)) {
109
+ pushRisk(categories, signals, 'long-running', 'long_running');
110
+ }
111
+ if (pipeCount >= 3) {
112
+ pushRisk(categories, signals, 'long-running', 'long_pipeline');
113
+ }
114
+ if (/(^|[^&])&(?!&)/.test(command)) {
115
+ pushRisk(categories, signals, 'process-control', 'background_task');
116
+ }
117
+ if (/\b(?:rm\s+-[a-zA-Z]*r|dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
118
+ pushRisk(categories, signals, 'destructive', 'destructive_command');
119
+ }
120
+ if (/\b(?:kill|pkill|killall)\b/.test(lowerCommand)) {
121
+ pushRisk(categories, signals, 'process-control', 'process_control');
122
+ }
123
+ if (/\b(?:systemctl|service|docker|kubectl)\s+(?:restart|stop|kill|delete|rm|down)\b/.test(lowerCommand)) {
124
+ pushRisk(categories, signals, 'service-control', 'service_control');
125
+ }
126
+ if (/\b(?:password|passwd|token|authorization|cookie|secret|private[_-]?key)\b/i.test(command)) {
127
+ pushRisk(categories, signals, 'credential-bearing', 'credential_bearing');
128
+ }
129
+ if (/\bsu\s+-?\s*[a-zA-Z_][a-zA-Z0-9_-]*\s+-c\b/.test(command)) {
130
+ pushRisk(categories, signals, 'user-switch', 'direct_su_command');
131
+ }
132
+ if (signals.length === 0) {
133
+ return undefined;
134
+ }
135
+ const highCategories = new Set(['destructive', 'process-control', 'service-control', 'long-running']);
136
+ const level = Array.from(categories).some((category) => highCategories.has(category)) ? 'high' : 'medium';
137
+ return {
138
+ level,
139
+ categories: Array.from(categories),
140
+ signals,
141
+ suggestion: signals.includes('direct_su_command')
142
+ ? '建议使用 ssh_exec 的 runAs 参数或 ssh_exec_as_user,避免手写 su 命令造成引用和环境加载差异'
143
+ : level === 'high'
144
+ ? '考虑用 ssh_exec_script、ssh_pty_start,或把输出重定向到远端文件后用 ssh_read_file 分块读取'
145
+ : '如输出较大,请设置 maxOutputSize 或重定向到远端文件后分块读取',
146
+ };
147
+ }
59
148
  async function handleExec(args) {
60
149
  try {
61
150
  const result = await sessionManager.exec(args.alias, args.command, {
@@ -63,8 +152,12 @@ async function handleExec(args) {
63
152
  cwd: args.cwd,
64
153
  env: args.env,
65
154
  pty: args.pty,
155
+ maxOutputSize: args.maxOutputSize,
156
+ runAs: args.runAs,
157
+ useLoginUser: args.useLoginUser,
158
+ loadProfile: args.loadProfile,
66
159
  });
67
- return formatResult(result);
160
+ return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
68
161
  }
69
162
  catch (error) {
70
163
  return formatError(error);
@@ -72,11 +165,24 @@ async function handleExec(args) {
72
165
  }
73
166
  async function handleExecAsUser(args) {
74
167
  try {
75
- const result = await sessionManager.execAsUser(args.alias, args.command, args.targetUser, {
168
+ if (args.targetUser) {
169
+ const result = await sessionManager.execAsUser(args.alias, args.command, args.targetUser, {
170
+ timeout: args.timeout,
171
+ cwd: args.cwd,
172
+ env: args.env,
173
+ maxOutputSize: args.maxOutputSize,
174
+ loadProfile: args.loadProfile,
175
+ });
176
+ return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
177
+ }
178
+ const result = await sessionManager.exec(args.alias, args.command, {
76
179
  timeout: args.timeout,
180
+ cwd: args.cwd,
181
+ env: args.env,
182
+ maxOutputSize: args.maxOutputSize,
77
183
  loadProfile: args.loadProfile,
78
184
  });
79
- return formatResult(result);
185
+ return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
80
186
  }
81
187
  catch (error) {
82
188
  return formatError(error);
@@ -86,6 +192,7 @@ async function handleExecSudo(args) {
86
192
  try {
87
193
  const result = await sessionManager.execSudo(args.alias, args.command, args.sudoPassword, {
88
194
  timeout: args.timeout,
195
+ maxOutputSize: args.maxOutputSize,
89
196
  });
90
197
  return formatResult(result);
91
198
  }
@@ -98,11 +205,13 @@ async function handleExecBatch(args) {
98
205
  const stopOnError = args.stopOnError !== false;
99
206
  const results = [];
100
207
  for (let i = 0; i < args.commands.length; i++) {
208
+ const commandRisk = classifyCommandRisk(args.commands[i]);
101
209
  try {
102
210
  const execResult = await sessionManager.exec(args.alias, args.commands[i], { timeout: args.timeout });
103
211
  results.push({
104
212
  index: i,
105
- command: args.commands[i],
213
+ commandRedacted: true,
214
+ commandRisk,
106
215
  ...execResult,
107
216
  });
108
217
  if (execResult.exitCode !== 0 && stopOnError) {
@@ -112,7 +221,8 @@ async function handleExecBatch(args) {
112
221
  catch (err) {
113
222
  results.push({
114
223
  index: i,
115
- command: args.commands[i],
224
+ commandRedacted: true,
225
+ commandRisk,
116
226
  success: false,
117
227
  error: err instanceof Error ? err.message : String(err),
118
228
  });
@@ -186,6 +296,95 @@ async function handleExecParallel(args) {
186
296
  return formatError(error);
187
297
  }
188
298
  }
299
+ async function cleanupRemoteScript(alias, remotePath) {
300
+ try {
301
+ const result = await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
302
+ timeout: 10000,
303
+ useLoginUser: true,
304
+ maxOutputSize: 4096,
305
+ });
306
+ if (result.success) {
307
+ return undefined;
308
+ }
309
+ return result.stderr || result.stdout || `cleanup failed with exit code ${result.exitCode}`;
310
+ }
311
+ catch (error) {
312
+ return error instanceof Error ? error.message : String(error);
313
+ }
314
+ }
315
+ function validateScriptUser(username) {
316
+ if (username !== undefined && !/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(username)) {
317
+ throw new Error(`Invalid username: ${username}`);
318
+ }
319
+ }
320
+ function resolveScriptUsers(args) {
321
+ const session = sessionManager.listSessions().find((item) => item.alias === args.alias);
322
+ return {
323
+ effectiveUser: args.targetUser ?? args.runAs ?? session?.runAs,
324
+ loginUser: session?.username,
325
+ };
326
+ }
327
+ async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser, timeout) {
328
+ const quotedPath = escapeShellArg(remotePath);
329
+ const ownershipCommand = effectiveUser && effectiveUser !== loginUser ? `chown ${escapeShellArg(effectiveUser)} ${quotedPath} && ` : '';
330
+ const result = await sessionManager.exec(alias, `${ownershipCommand}chmod 700 ${quotedPath}`, {
331
+ timeout,
332
+ useLoginUser: true,
333
+ maxOutputSize: 4096,
334
+ });
335
+ if (!result.success) {
336
+ const reason = result.stderr || result.stdout || `exit code ${result.exitCode}`;
337
+ throw new Error(`prepare remote script failed: ${reason}`);
338
+ }
339
+ }
340
+ async function handleExecScript(args) {
341
+ let remotePath;
342
+ try {
343
+ const interpreter = args.interpreter ?? 'bash';
344
+ const { effectiveUser, loginUser } = resolveScriptUsers(args);
345
+ validateScriptUser(effectiveUser);
346
+ const tempResult = await sessionManager.exec(args.alias, 'mktemp /tmp/mcp-ssh-script.XXXXXX', {
347
+ timeout: args.timeout,
348
+ useLoginUser: true,
349
+ maxOutputSize: 4096,
350
+ });
351
+ remotePath = tempResult.stdout.trim();
352
+ if (!tempResult.success || remotePath.length === 0) {
353
+ return formatResult({ success: false, error: tempResult.stderr || 'mktemp failed' });
354
+ }
355
+ await fileOps.writeFile(args.alias, remotePath, args.script, false);
356
+ await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout);
357
+ const command = `${escapeShellArg(interpreter)} ${escapeShellArg(remotePath)}`;
358
+ const execOptions = {
359
+ timeout: args.timeout,
360
+ cwd: args.cwd,
361
+ env: args.env,
362
+ maxOutputSize: args.maxOutputSize,
363
+ runAs: args.targetUser ?? args.runAs,
364
+ };
365
+ const result = args.targetUser
366
+ ? await sessionManager.execAsUser(args.alias, command, args.targetUser, execOptions)
367
+ : await sessionManager.exec(args.alias, command, execOptions);
368
+ const cleanupWarning = remotePath && args.keepScript !== true ? await cleanupRemoteScript(args.alias, remotePath) : undefined;
369
+ return formatResult({
370
+ ...result,
371
+ remotePath: args.keepScript ? remotePath : undefined,
372
+ kept: args.keepScript === true,
373
+ cleanupWarning,
374
+ });
375
+ }
376
+ catch (error) {
377
+ const cleanupWarning = remotePath && args.keepScript !== true ? await cleanupRemoteScript(args.alias, remotePath) : undefined;
378
+ if (cleanupWarning) {
379
+ return formatResult({
380
+ success: false,
381
+ error: error instanceof Error ? error.message : String(error),
382
+ cleanupWarning,
383
+ });
384
+ }
385
+ return formatError(error);
386
+ }
387
+ }
189
388
  // ========== Register ==========
190
389
  export function registerExecTools(server) {
191
390
  server.registerTool('ssh_exec', {
@@ -197,12 +396,12 @@ export function registerExecTools(server) {
197
396
  server.registerTool('ssh_exec_as_user', {
198
397
  description: `以其他用户身份执行命令(通过 su 切换)
199
398
 
200
- 适用场景: SSH 以 root 登录,但需要以其他用户(如 caros)执行命令
399
+ 适用场景: SSH 以管理员账号登录,但需要以应用用户执行命令
201
400
 
202
401
  默认加载目标用户的 shell 配置以获取环境变量,如果 profile 加载耗时过长导致超时,设 loadProfile=false 跳过
203
402
  支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
204
403
 
205
- 示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="caros")`,
404
+ 示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="appuser")`,
206
405
  inputSchema: execAsUserSchema,
207
406
  }, (args) => handleExecAsUser(args));
208
407
  server.registerTool('ssh_exec_sudo', {
@@ -228,4 +427,8 @@ export function registerExecTools(server) {
228
427
  返回每个主机的执行结果`,
229
428
  inputSchema: execParallelSchema,
230
429
  }, (args) => handleExecParallel(args));
430
+ server.registerTool('ssh_exec_script', {
431
+ description: '上传远端临时脚本并执行,默认执行后清理脚本',
432
+ inputSchema: execScriptSchema,
433
+ }, (args) => handleExecScript(args));
231
434
  }