@pyrokine/mcp-ssh 2.0.2 → 2.1.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.
- package/README.md +100 -19
- package/README_zh.md +94 -18
- package/dist/file-ops.d.ts +67 -5
- package/dist/file-ops.js +400 -81
- package/dist/pty-manager.d.ts +6 -0
- package/dist/pty-manager.js +19 -0
- package/dist/session-manager.d.ts +14 -0
- package/dist/session-manager.js +254 -78
- package/dist/tools/connection.js +106 -20
- package/dist/tools/exec.js +201 -9
- package/dist/tools/file.js +288 -8
- package/dist/tools/forward.js +2 -2
- package/dist/tools/pty.js +1 -1
- package/dist/tools/utils.js +9 -1
- package/dist/types.d.ts +38 -0
- package/package.json +7 -7
package/dist/tools/connection.js
CHANGED
|
@@ -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
|
-
|
|
47
|
-
|
|
48
|
-
let
|
|
49
|
-
let
|
|
50
|
-
let
|
|
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 (
|
|
95
|
+
if (configHost) {
|
|
53
96
|
const allHosts = parseSSHConfig(args.configPath);
|
|
54
|
-
const hostConfig = allHosts.find((h) => h.host ===
|
|
97
|
+
const hostConfig = allHosts.find((h) => h.host === configHost);
|
|
55
98
|
if (!hostConfig) {
|
|
56
|
-
return formatResult({
|
|
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:
|
|
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
|
|
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:
|
|
178
|
+
port: finalPort,
|
|
108
179
|
username: user,
|
|
109
|
-
password
|
|
180
|
+
password,
|
|
110
181
|
privateKeyPath: keyPath,
|
|
111
|
-
alias:
|
|
112
|
-
|
|
113
|
-
|
|
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
|
-
|
|
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) {
|
|
@@ -187,8 +273,8 @@ export function registerConnectionTools(server) {
|
|
|
187
273
|
|
|
188
274
|
示例:
|
|
189
275
|
- 使用 ssh config: ssh_connect(configHost="myserver")
|
|
190
|
-
- 密钥认证: ssh_connect(host="
|
|
191
|
-
- 跳板机: ssh_connect(host="
|
|
276
|
+
- 密钥认证: ssh_connect(host="<server-host>", user="<ssh-user>", keyPath="/home/.ssh/id_rsa")
|
|
277
|
+
- 跳板机: ssh_connect(host="<internal-host>", user="<ssh-user>", keyPath="...", jumpHost={host:"<bastion-host>", user:"<ssh-user>", keyPath:"..."})`,
|
|
192
278
|
inputSchema: connectSchema,
|
|
193
279
|
}, (args) => handleConnect(args));
|
|
194
280
|
server.registerTool('ssh_disconnect', {
|
package/dist/tools/exec.js
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
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 { escapeShellArg, formatError, formatResult } from './utils.js'; // ========== Schemas ==========
|
|
10
11
|
// ========== Schemas ==========
|
|
11
12
|
const execSchema = z.object({
|
|
12
13
|
alias: z.string().describe('连接别名'),
|
|
@@ -16,14 +17,21 @@ const execSchema = z.object({
|
|
|
16
17
|
.optional()
|
|
17
18
|
.describe('超时(毫秒),默认 30000,长时间命令可设更大值如 600000(10 分钟),或用 ssh_pty_start 替代'),
|
|
18
19
|
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
19
|
-
env: z.record(z.string()).optional().describe('额外环境变量'),
|
|
20
|
+
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
20
21
|
pty: z.boolean().optional().describe('是否使用 PTY 模式(用于 top 等交互式命令)'),
|
|
22
|
+
maxOutputSize: z.number().optional().describe('最大输出字符数,超过后截断并返回提示'),
|
|
23
|
+
runAs: z.string().optional().describe('本次命令使用的目标用户,覆盖连接级 runAs'),
|
|
24
|
+
useLoginUser: z.boolean().optional().describe('设为 true 时跳过连接级 runAs,直接以登录用户执行'),
|
|
25
|
+
loadProfile: z.boolean().optional().describe('runAs 执行时是否加载目标用户 shell 配置,默认 true'),
|
|
21
26
|
});
|
|
22
27
|
const execAsUserSchema = z.object({
|
|
23
28
|
alias: z.string().describe('连接别名'),
|
|
24
29
|
command: z.string().describe('要执行的命令'),
|
|
25
|
-
targetUser: z.string().describe('
|
|
30
|
+
targetUser: z.string().optional().describe('目标用户名,不传时使用连接级 runAs'),
|
|
26
31
|
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
32
|
+
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
33
|
+
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
34
|
+
maxOutputSize: z.number().optional().describe('最大输出字符数,超过后截断并返回提示'),
|
|
27
35
|
loadProfile: z
|
|
28
36
|
.boolean()
|
|
29
37
|
.optional()
|
|
@@ -34,6 +42,7 @@ const execSudoSchema = z.object({
|
|
|
34
42
|
command: z.string().describe('要执行的命令'),
|
|
35
43
|
sudoPassword: z.string().optional().describe('sudo 密码(如果需要)'),
|
|
36
44
|
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
45
|
+
maxOutputSize: z.number().optional().describe('最大输出字符数,超过后截断并返回提示'),
|
|
37
46
|
});
|
|
38
47
|
const execBatchSchema = z.object({
|
|
39
48
|
alias: z.string().describe('连接别名'),
|
|
@@ -55,7 +64,79 @@ const execParallelSchema = z.object({
|
|
|
55
64
|
command: z.string().describe('要执行的命令'),
|
|
56
65
|
timeout: z.number().optional().describe('每个命令的超时(毫秒),默认 30000'),
|
|
57
66
|
});
|
|
58
|
-
|
|
67
|
+
const execScriptSchema = z.object({
|
|
68
|
+
alias: z.string().describe('连接别名'),
|
|
69
|
+
script: z.string().describe('脚本内容'),
|
|
70
|
+
interpreter: z.string().optional().describe('解释器,默认 bash'),
|
|
71
|
+
targetUser: z.string().optional().describe('目标用户名,优先级高于 runAs'),
|
|
72
|
+
runAs: z.string().optional().describe('本次脚本使用的目标用户'),
|
|
73
|
+
cwd: z.string().optional().describe('工作目录(可选)'),
|
|
74
|
+
env: z.record(z.string(), z.string()).optional().describe('额外环境变量'),
|
|
75
|
+
timeout: z.number().optional().describe('超时(毫秒)'),
|
|
76
|
+
keepScript: z.boolean().optional().describe('是否保留远端临时脚本,默认 false'),
|
|
77
|
+
maxOutputSize: z.number().optional().describe('最大输出字符数,超过后截断并返回提示'),
|
|
78
|
+
});
|
|
79
|
+
function pushRisk(categories, signals, category, signal) {
|
|
80
|
+
categories.add(category);
|
|
81
|
+
signals.push(signal);
|
|
82
|
+
}
|
|
83
|
+
function classifyCommandRisk(command) {
|
|
84
|
+
const signals = [];
|
|
85
|
+
const categories = new Set();
|
|
86
|
+
const pipeCount = (command.match(/\|/g) ?? []).length;
|
|
87
|
+
const lowerCommand = command.toLowerCase();
|
|
88
|
+
if (command.length > 500) {
|
|
89
|
+
pushRisk(categories, signals, 'long-running', 'long_command');
|
|
90
|
+
}
|
|
91
|
+
if (/\bgrep\s+(?:-\S*R|--recursive)\b/.test(command)) {
|
|
92
|
+
pushRisk(categories, signals, 'long-running', 'recursive_grep');
|
|
93
|
+
}
|
|
94
|
+
if (/\bfind\b/.test(command) && !/\s-maxdepth\s+\d+/.test(command)) {
|
|
95
|
+
pushRisk(categories, signals, 'long-running', 'unbounded_find');
|
|
96
|
+
}
|
|
97
|
+
if (/\b(?:python|python3|node|perl|ruby)\b/.test(command)) {
|
|
98
|
+
pushRisk(categories, signals, 'script-execution', 'interpreter_script');
|
|
99
|
+
}
|
|
100
|
+
if (/\bsleep\s+\d{2,}\b/.test(command) || /\b(?:tail\s+-f|journalctl\s+-f|watch|top|htop)\b/.test(command)) {
|
|
101
|
+
pushRisk(categories, signals, 'long-running', 'long_running');
|
|
102
|
+
}
|
|
103
|
+
if (pipeCount >= 3) {
|
|
104
|
+
pushRisk(categories, signals, 'long-running', 'long_pipeline');
|
|
105
|
+
}
|
|
106
|
+
if (/(?:^|[;&])\s*[^;&]+&\s*(?:$|[;&])/.test(command)) {
|
|
107
|
+
pushRisk(categories, signals, 'process-control', 'background_task');
|
|
108
|
+
}
|
|
109
|
+
if (/\b(?:rm\s+-[a-zA-Z]*r|dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
|
|
110
|
+
pushRisk(categories, signals, 'destructive', 'destructive_command');
|
|
111
|
+
}
|
|
112
|
+
if (/\b(?:kill|pkill|killall)\b/.test(lowerCommand)) {
|
|
113
|
+
pushRisk(categories, signals, 'process-control', 'process_control');
|
|
114
|
+
}
|
|
115
|
+
if (/\b(?:systemctl|service|docker|kubectl)\s+(?:restart|stop|kill|delete|rm|down)\b/.test(lowerCommand)) {
|
|
116
|
+
pushRisk(categories, signals, 'service-control', 'service_control');
|
|
117
|
+
}
|
|
118
|
+
if (/\b(?:password|passwd|token|authorization|cookie|secret|private[_-]?key)\b/i.test(command)) {
|
|
119
|
+
pushRisk(categories, signals, 'credential-bearing', 'credential_bearing');
|
|
120
|
+
}
|
|
121
|
+
if (/\bsu\s+-?\s*[a-zA-Z_][a-zA-Z0-9_-]*\s+-c\b/.test(command)) {
|
|
122
|
+
pushRisk(categories, signals, 'user-switch', 'direct_su_command');
|
|
123
|
+
}
|
|
124
|
+
if (signals.length === 0) {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
const highCategories = new Set(['destructive', 'process-control', 'service-control', 'long-running']);
|
|
128
|
+
const level = Array.from(categories).some((category) => highCategories.has(category)) ? 'high' : 'medium';
|
|
129
|
+
return {
|
|
130
|
+
level,
|
|
131
|
+
categories: Array.from(categories),
|
|
132
|
+
signals,
|
|
133
|
+
suggestion: signals.includes('direct_su_command')
|
|
134
|
+
? '建议使用 ssh_exec 的 runAs 参数或 ssh_exec_as_user,避免手写 su 命令造成引用和环境加载差异'
|
|
135
|
+
: level === 'high'
|
|
136
|
+
? '考虑用 ssh_exec_script、ssh_pty_start,或把输出重定向到远端文件后用 ssh_read_file 分块读取'
|
|
137
|
+
: '如输出较大,请设置 maxOutputSize 或重定向到远端文件后分块读取',
|
|
138
|
+
};
|
|
139
|
+
}
|
|
59
140
|
async function handleExec(args) {
|
|
60
141
|
try {
|
|
61
142
|
const result = await sessionManager.exec(args.alias, args.command, {
|
|
@@ -63,8 +144,12 @@ async function handleExec(args) {
|
|
|
63
144
|
cwd: args.cwd,
|
|
64
145
|
env: args.env,
|
|
65
146
|
pty: args.pty,
|
|
147
|
+
maxOutputSize: args.maxOutputSize,
|
|
148
|
+
runAs: args.runAs,
|
|
149
|
+
useLoginUser: args.useLoginUser,
|
|
150
|
+
loadProfile: args.loadProfile,
|
|
66
151
|
});
|
|
67
|
-
return formatResult(result);
|
|
152
|
+
return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
|
|
68
153
|
}
|
|
69
154
|
catch (error) {
|
|
70
155
|
return formatError(error);
|
|
@@ -72,11 +157,24 @@ async function handleExec(args) {
|
|
|
72
157
|
}
|
|
73
158
|
async function handleExecAsUser(args) {
|
|
74
159
|
try {
|
|
75
|
-
|
|
160
|
+
if (args.targetUser) {
|
|
161
|
+
const result = await sessionManager.execAsUser(args.alias, args.command, args.targetUser, {
|
|
162
|
+
timeout: args.timeout,
|
|
163
|
+
cwd: args.cwd,
|
|
164
|
+
env: args.env,
|
|
165
|
+
maxOutputSize: args.maxOutputSize,
|
|
166
|
+
loadProfile: args.loadProfile,
|
|
167
|
+
});
|
|
168
|
+
return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
|
|
169
|
+
}
|
|
170
|
+
const result = await sessionManager.exec(args.alias, args.command, {
|
|
76
171
|
timeout: args.timeout,
|
|
172
|
+
cwd: args.cwd,
|
|
173
|
+
env: args.env,
|
|
174
|
+
maxOutputSize: args.maxOutputSize,
|
|
77
175
|
loadProfile: args.loadProfile,
|
|
78
176
|
});
|
|
79
|
-
return formatResult(result);
|
|
177
|
+
return formatResult({ ...result, commandRisk: classifyCommandRisk(args.command) });
|
|
80
178
|
}
|
|
81
179
|
catch (error) {
|
|
82
180
|
return formatError(error);
|
|
@@ -86,6 +184,7 @@ async function handleExecSudo(args) {
|
|
|
86
184
|
try {
|
|
87
185
|
const result = await sessionManager.execSudo(args.alias, args.command, args.sudoPassword, {
|
|
88
186
|
timeout: args.timeout,
|
|
187
|
+
maxOutputSize: args.maxOutputSize,
|
|
89
188
|
});
|
|
90
189
|
return formatResult(result);
|
|
91
190
|
}
|
|
@@ -186,6 +285,95 @@ async function handleExecParallel(args) {
|
|
|
186
285
|
return formatError(error);
|
|
187
286
|
}
|
|
188
287
|
}
|
|
288
|
+
async function cleanupRemoteScript(alias, remotePath) {
|
|
289
|
+
try {
|
|
290
|
+
const result = await sessionManager.exec(alias, `rm -f ${escapeShellArg(remotePath)}`, {
|
|
291
|
+
timeout: 10000,
|
|
292
|
+
useLoginUser: true,
|
|
293
|
+
maxOutputSize: 4096,
|
|
294
|
+
});
|
|
295
|
+
if (result.success) {
|
|
296
|
+
return undefined;
|
|
297
|
+
}
|
|
298
|
+
return result.stderr || result.stdout || `cleanup failed with exit code ${result.exitCode}`;
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
return error instanceof Error ? error.message : String(error);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function validateScriptUser(username) {
|
|
305
|
+
if (username !== undefined && !/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(username)) {
|
|
306
|
+
throw new Error(`Invalid username: ${username}`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function resolveScriptUsers(args) {
|
|
310
|
+
const session = sessionManager.listSessions().find((item) => item.alias === args.alias);
|
|
311
|
+
return {
|
|
312
|
+
effectiveUser: args.targetUser ?? args.runAs ?? session?.runAs,
|
|
313
|
+
loginUser: session?.username,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
async function prepareRemoteScript(alias, remotePath, effectiveUser, loginUser, timeout) {
|
|
317
|
+
const quotedPath = escapeShellArg(remotePath);
|
|
318
|
+
const ownershipCommand = effectiveUser && effectiveUser !== loginUser ? `chown ${escapeShellArg(effectiveUser)} ${quotedPath} && ` : '';
|
|
319
|
+
const result = await sessionManager.exec(alias, `${ownershipCommand}chmod 700 ${quotedPath}`, {
|
|
320
|
+
timeout,
|
|
321
|
+
useLoginUser: true,
|
|
322
|
+
maxOutputSize: 4096,
|
|
323
|
+
});
|
|
324
|
+
if (!result.success) {
|
|
325
|
+
const reason = result.stderr || result.stdout || `exit code ${result.exitCode}`;
|
|
326
|
+
throw new Error(`prepare remote script failed: ${reason}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async function handleExecScript(args) {
|
|
330
|
+
let remotePath;
|
|
331
|
+
try {
|
|
332
|
+
const interpreter = args.interpreter ?? 'bash';
|
|
333
|
+
const { effectiveUser, loginUser } = resolveScriptUsers(args);
|
|
334
|
+
validateScriptUser(effectiveUser);
|
|
335
|
+
const tempResult = await sessionManager.exec(args.alias, 'mktemp /tmp/mcp-ssh-script.XXXXXX', {
|
|
336
|
+
timeout: args.timeout,
|
|
337
|
+
useLoginUser: true,
|
|
338
|
+
maxOutputSize: 4096,
|
|
339
|
+
});
|
|
340
|
+
remotePath = tempResult.stdout.trim();
|
|
341
|
+
if (!tempResult.success || remotePath.length === 0) {
|
|
342
|
+
return formatResult({ success: false, error: tempResult.stderr || 'mktemp failed' });
|
|
343
|
+
}
|
|
344
|
+
await fileOps.writeFile(args.alias, remotePath, args.script, false);
|
|
345
|
+
await prepareRemoteScript(args.alias, remotePath, effectiveUser, loginUser, args.timeout);
|
|
346
|
+
const command = `${escapeShellArg(interpreter)} ${escapeShellArg(remotePath)}`;
|
|
347
|
+
const execOptions = {
|
|
348
|
+
timeout: args.timeout,
|
|
349
|
+
cwd: args.cwd,
|
|
350
|
+
env: args.env,
|
|
351
|
+
maxOutputSize: args.maxOutputSize,
|
|
352
|
+
runAs: args.targetUser ?? args.runAs,
|
|
353
|
+
};
|
|
354
|
+
const result = args.targetUser
|
|
355
|
+
? await sessionManager.execAsUser(args.alias, command, args.targetUser, execOptions)
|
|
356
|
+
: await sessionManager.exec(args.alias, command, execOptions);
|
|
357
|
+
const cleanupWarning = remotePath && args.keepScript !== true ? await cleanupRemoteScript(args.alias, remotePath) : undefined;
|
|
358
|
+
return formatResult({
|
|
359
|
+
...result,
|
|
360
|
+
remotePath: args.keepScript ? remotePath : undefined,
|
|
361
|
+
kept: args.keepScript === true,
|
|
362
|
+
cleanupWarning,
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
const cleanupWarning = remotePath && args.keepScript !== true ? await cleanupRemoteScript(args.alias, remotePath) : undefined;
|
|
367
|
+
if (cleanupWarning) {
|
|
368
|
+
return formatResult({
|
|
369
|
+
success: false,
|
|
370
|
+
error: error instanceof Error ? error.message : String(error),
|
|
371
|
+
cleanupWarning,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
return formatError(error);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
189
377
|
// ========== Register ==========
|
|
190
378
|
export function registerExecTools(server) {
|
|
191
379
|
server.registerTool('ssh_exec', {
|
|
@@ -197,12 +385,12 @@ export function registerExecTools(server) {
|
|
|
197
385
|
server.registerTool('ssh_exec_as_user', {
|
|
198
386
|
description: `以其他用户身份执行命令(通过 su 切换)
|
|
199
387
|
|
|
200
|
-
适用场景: SSH
|
|
388
|
+
适用场景: SSH 以管理员账号登录,但需要以应用用户执行命令
|
|
201
389
|
|
|
202
390
|
默认加载目标用户的 shell 配置以获取环境变量,如果 profile 加载耗时过长导致超时,设 loadProfile=false 跳过
|
|
203
391
|
支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
|
|
204
392
|
|
|
205
|
-
示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="
|
|
393
|
+
示例: ssh_exec_as_user(alias="server", command="whoami", targetUser="appuser")`,
|
|
206
394
|
inputSchema: execAsUserSchema,
|
|
207
395
|
}, (args) => handleExecAsUser(args));
|
|
208
396
|
server.registerTool('ssh_exec_sudo', {
|
|
@@ -228,4 +416,8 @@ export function registerExecTools(server) {
|
|
|
228
416
|
返回每个主机的执行结果`,
|
|
229
417
|
inputSchema: execParallelSchema,
|
|
230
418
|
}, (args) => handleExecParallel(args));
|
|
419
|
+
server.registerTool('ssh_exec_script', {
|
|
420
|
+
description: '上传远端临时脚本并执行,默认执行后清理脚本',
|
|
421
|
+
inputSchema: execScriptSchema,
|
|
422
|
+
}, (args) => handleExecScript(args));
|
|
231
423
|
}
|