@pyrokine/mcp-ssh 1.1.2 → 1.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.
- package/README.md +3 -1
- package/README_zh.md +3 -1
- package/dist/file-ops.d.ts +7 -10
- package/dist/file-ops.js +74 -172
- package/dist/forward-manager.d.ts +33 -0
- package/dist/forward-manager.js +185 -0
- package/dist/index.js +8 -953
- package/dist/pty-manager.d.ts +37 -0
- package/dist/pty-manager.js +169 -0
- package/dist/session-manager.d.ts +28 -86
- package/dist/session-manager.js +131 -441
- package/dist/ssh-config.d.ts +0 -4
- package/dist/ssh-config.js +1 -8
- package/dist/tools/connection.d.ts +7 -0
- package/dist/tools/connection.js +215 -0
- package/dist/tools/exec.d.ts +8 -0
- package/dist/tools/exec.js +221 -0
- package/dist/tools/file.d.ts +8 -0
- package/dist/tools/file.js +192 -0
- package/dist/tools/forward.d.ts +7 -0
- package/dist/tools/forward.js +116 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/pty.d.ts +7 -0
- package/dist/tools/pty.js +178 -0
- package/dist/tools/utils.d.ts +22 -0
- package/dist/tools/utils.js +21 -0
- package/dist/types.d.ts +0 -7
- package/package.json +3 -2
- package/src/file-ops.ts +117 -212
- package/src/forward-manager.ts +257 -0
- package/src/index.ts +17 -1099
- package/src/pty-manager.ts +220 -0
- package/src/session-manager.ts +166 -532
- package/src/ssh-config.ts +1 -8
- package/src/tools/connection.ts +240 -0
- package/src/tools/exec.ts +260 -0
- package/src/tools/file.ts +219 -0
- package/src/tools/forward.ts +141 -0
- package/src/tools/index.ts +9 -0
- package/src/tools/pty.ts +203 -0
- package/src/tools/utils.ts +23 -0
- package/src/types.ts +0 -9
package/dist/session-manager.js
CHANGED
|
@@ -7,24 +7,22 @@
|
|
|
7
7
|
* - 自动重连
|
|
8
8
|
* - 会话持久化
|
|
9
9
|
*/
|
|
10
|
-
import xterm from '@xterm/headless';
|
|
11
10
|
import * as fs from 'fs';
|
|
12
|
-
import * as net from 'net';
|
|
13
11
|
import * as path from 'path';
|
|
14
12
|
import { Client } from 'ssh2';
|
|
15
|
-
|
|
13
|
+
import { ForwardManager } from './forward-manager.js';
|
|
14
|
+
import { PtyManager } from './pty-manager.js';
|
|
16
15
|
export class SessionManager {
|
|
17
16
|
sessions = new Map();
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
ptyIdCounter = 0;
|
|
21
|
-
forwardIdCounter = 0;
|
|
17
|
+
ptyManager = new PtyManager();
|
|
18
|
+
forwardManager = new ForwardManager();
|
|
22
19
|
persistPath;
|
|
23
20
|
defaultKeepaliveInterval = 30000; // 30秒
|
|
24
21
|
defaultKeepaliveCountMax = 3;
|
|
25
22
|
defaultTimeout = 30000; // 30秒
|
|
26
23
|
maxReconnectAttempts = 3;
|
|
27
|
-
|
|
24
|
+
defaultMaxOutputSize = 10 * 1024 * 1024; // 10MB
|
|
25
|
+
reconnectDelay = 5000; // 5秒
|
|
28
26
|
constructor(persistPath) {
|
|
29
27
|
this.persistPath = persistPath || path.join(process.env.HOME || '/tmp', '.ssh-mcp-pro', 'sessions.json');
|
|
30
28
|
this.ensurePersistDir();
|
|
@@ -69,8 +67,7 @@ export class SessionManager {
|
|
|
69
67
|
const jumpSession = this.sessions.get(jumpAlias);
|
|
70
68
|
if (jumpSession) {
|
|
71
69
|
// 通过跳板机建立连接
|
|
72
|
-
|
|
73
|
-
connectConfig.sock = stream;
|
|
70
|
+
connectConfig.sock = await this.forwardConnection(jumpSession.client, config.host, config.port || 22);
|
|
74
71
|
}
|
|
75
72
|
}
|
|
76
73
|
return new Promise((resolve, reject) => {
|
|
@@ -82,6 +79,7 @@ export class SessionManager {
|
|
|
82
79
|
lastUsedAt: Date.now(),
|
|
83
80
|
reconnectAttempts: 0,
|
|
84
81
|
connected: true,
|
|
82
|
+
manualClose: false,
|
|
85
83
|
};
|
|
86
84
|
this.sessions.set(alias, session);
|
|
87
85
|
this.persistSessions();
|
|
@@ -89,22 +87,21 @@ export class SessionManager {
|
|
|
89
87
|
});
|
|
90
88
|
client.on('error', (err) => {
|
|
91
89
|
const session = this.sessions.get(alias);
|
|
92
|
-
if (session) {
|
|
90
|
+
if (session && session.client === client) {
|
|
93
91
|
session.connected = false;
|
|
94
92
|
}
|
|
95
|
-
|
|
93
|
+
const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`;
|
|
94
|
+
const suggestion = this.diagnoseConnectionError(err);
|
|
95
|
+
reject(new Error(`SSH connection to ${target} failed: ${err.message}${suggestion ?
|
|
96
|
+
` (${suggestion})` :
|
|
97
|
+
''}`));
|
|
96
98
|
});
|
|
97
99
|
client.on('close', () => {
|
|
98
100
|
const session = this.sessions.get(alias);
|
|
99
|
-
if (session) {
|
|
101
|
+
if (session && session.client === client) {
|
|
100
102
|
session.connected = false;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
session.reconnectAttempts++;
|
|
104
|
-
setTimeout(() => {
|
|
105
|
-
this.reconnect(alias).catch(() => {
|
|
106
|
-
});
|
|
107
|
-
}, 5000); // 5 秒后重连
|
|
103
|
+
if (!session.manualClose) {
|
|
104
|
+
this.scheduleReconnect(alias);
|
|
108
105
|
}
|
|
109
106
|
}
|
|
110
107
|
});
|
|
@@ -119,10 +116,12 @@ export class SessionManager {
|
|
|
119
116
|
if (!session) {
|
|
120
117
|
throw new Error(`Session ${alias} not found`);
|
|
121
118
|
}
|
|
119
|
+
session.manualClose = true;
|
|
120
|
+
session.connected = false;
|
|
122
121
|
try {
|
|
123
122
|
session.client.end();
|
|
124
123
|
}
|
|
125
|
-
catch {
|
|
124
|
+
catch { /* 忽略已关闭的连接 */
|
|
126
125
|
}
|
|
127
126
|
await this.connect(session.config);
|
|
128
127
|
}
|
|
@@ -132,10 +131,14 @@ export class SessionManager {
|
|
|
132
131
|
disconnect(alias) {
|
|
133
132
|
const session = this.sessions.get(alias);
|
|
134
133
|
if (session) {
|
|
134
|
+
session.manualClose = true;
|
|
135
|
+
// 清理关联的 PTY 和 forward 资源
|
|
136
|
+
this.ptyManager.closeByAlias(alias);
|
|
137
|
+
this.forwardManager.closeByAlias(alias);
|
|
135
138
|
try {
|
|
136
139
|
session.client.end();
|
|
137
140
|
}
|
|
138
|
-
catch {
|
|
141
|
+
catch { /* 忽略已关闭的连接 */
|
|
139
142
|
}
|
|
140
143
|
this.sessions.delete(alias);
|
|
141
144
|
this.persistSessions();
|
|
@@ -143,14 +146,6 @@ export class SessionManager {
|
|
|
143
146
|
}
|
|
144
147
|
return false;
|
|
145
148
|
}
|
|
146
|
-
/**
|
|
147
|
-
* 断开所有连接
|
|
148
|
-
*/
|
|
149
|
-
disconnectAll() {
|
|
150
|
-
for (const alias of this.sessions.keys()) {
|
|
151
|
-
this.disconnect(alias);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
149
|
/**
|
|
155
150
|
* 获取会话
|
|
156
151
|
*/
|
|
@@ -190,29 +185,8 @@ export class SessionManager {
|
|
|
190
185
|
async exec(alias, command, options = {}) {
|
|
191
186
|
const session = this.getSession(alias);
|
|
192
187
|
const startTime = Date.now();
|
|
193
|
-
const maxOutputSize = options.maxOutputSize ||
|
|
194
|
-
|
|
195
|
-
let fullCommand = command;
|
|
196
|
-
const env = { ...session.config.env, ...options.env };
|
|
197
|
-
if (Object.keys(env).length > 0) {
|
|
198
|
-
// 校验并过滤环境变量名
|
|
199
|
-
const validEnvEntries = Object.entries(env).filter(([k]) => {
|
|
200
|
-
if (!this.isValidEnvKey(k)) {
|
|
201
|
-
// 静默忽略非法环境变量名
|
|
202
|
-
return false;
|
|
203
|
-
}
|
|
204
|
-
return true;
|
|
205
|
-
});
|
|
206
|
-
if (validEnvEntries.length > 0) {
|
|
207
|
-
const envStr = validEnvEntries
|
|
208
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
209
|
-
.join('; ');
|
|
210
|
-
fullCommand = `${envStr}; ${command}`;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
if (options.cwd) {
|
|
214
|
-
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
215
|
-
}
|
|
188
|
+
const maxOutputSize = options.maxOutputSize || this.defaultMaxOutputSize;
|
|
189
|
+
const fullCommand = this.buildCommand(command, session, options);
|
|
216
190
|
return new Promise((resolve, reject) => {
|
|
217
191
|
const timeout = options.timeout || this.defaultTimeout;
|
|
218
192
|
let timeoutId = null;
|
|
@@ -280,10 +254,11 @@ export class SessionManager {
|
|
|
280
254
|
}
|
|
281
255
|
/**
|
|
282
256
|
* 以其他用户身份执行命令
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
257
|
+
*
|
|
258
|
+
* options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
|
|
259
|
+
* su -c 创建非交互式 shell,不会自动执行 rc 文件,
|
|
260
|
+
* 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
|
|
261
|
+
* 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
|
|
287
262
|
*/
|
|
288
263
|
async execAsUser(alias, command, targetUser, options = {}) {
|
|
289
264
|
// 校验用户名防止注入
|
|
@@ -327,332 +302,64 @@ export class SessionManager {
|
|
|
327
302
|
});
|
|
328
303
|
});
|
|
329
304
|
}
|
|
330
|
-
|
|
331
|
-
* 加载持久化的会话信息(仅用于显示,不自动重连)
|
|
332
|
-
*/
|
|
333
|
-
loadPersistedSessions() {
|
|
334
|
-
try {
|
|
335
|
-
if (fs.existsSync(this.persistPath)) {
|
|
336
|
-
return JSON.parse(fs.readFileSync(this.persistPath, 'utf-8'));
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
catch {
|
|
340
|
-
}
|
|
341
|
-
return [];
|
|
342
|
-
}
|
|
343
|
-
/**
|
|
344
|
-
* 启动持久化 PTY 会话
|
|
345
|
-
*/
|
|
305
|
+
// ===== PTY 委托 =====
|
|
346
306
|
async ptyStart(alias, command, options = {}) {
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
const cols = options.cols || 80;
|
|
351
|
-
const term = options.term || 'xterm-256color';
|
|
352
|
-
const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize;
|
|
353
|
-
// 构建完整命令
|
|
354
|
-
let fullCommand = command;
|
|
355
|
-
const env = { ...session.config.env, ...options.env };
|
|
356
|
-
if (Object.keys(env).length > 0) {
|
|
357
|
-
const envStr = Object.entries(env)
|
|
358
|
-
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
359
|
-
.join('; ');
|
|
360
|
-
fullCommand = `${envStr}; ${command}`;
|
|
361
|
-
}
|
|
362
|
-
if (options.cwd) {
|
|
363
|
-
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
364
|
-
}
|
|
365
|
-
return new Promise((resolve, reject) => {
|
|
366
|
-
session.client.exec(fullCommand, {
|
|
367
|
-
pty: { rows, cols, term },
|
|
368
|
-
}, (err, stream) => {
|
|
369
|
-
if (err) {
|
|
370
|
-
reject(new Error(`PTY start failed: ${err.message}`));
|
|
371
|
-
return;
|
|
372
|
-
}
|
|
373
|
-
// 创建 xterm headless 终端仿真器
|
|
374
|
-
const terminal = new Terminal({
|
|
375
|
-
rows,
|
|
376
|
-
cols,
|
|
377
|
-
allowProposedApi: true,
|
|
378
|
-
});
|
|
379
|
-
const ptySession = {
|
|
380
|
-
id: ptyId,
|
|
381
|
-
alias,
|
|
382
|
-
command,
|
|
383
|
-
stream,
|
|
384
|
-
terminal,
|
|
385
|
-
rows,
|
|
386
|
-
cols,
|
|
387
|
-
createdAt: Date.now(),
|
|
388
|
-
lastReadAt: Date.now(),
|
|
389
|
-
rawBuffer: '',
|
|
390
|
-
maxBufferSize,
|
|
391
|
-
active: true,
|
|
392
|
-
};
|
|
393
|
-
// 监听输出数据
|
|
394
|
-
stream.on('data', (data) => {
|
|
395
|
-
if (!ptySession.active) {
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
const chunk = data.toString('utf-8');
|
|
399
|
-
// 写入终端仿真器(解析 ANSI 序列)
|
|
400
|
-
terminal.write(chunk);
|
|
401
|
-
// 同时保留原始流(用于 raw 模式)
|
|
402
|
-
ptySession.rawBuffer += chunk;
|
|
403
|
-
if (ptySession.rawBuffer.length > maxBufferSize) {
|
|
404
|
-
ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize);
|
|
405
|
-
}
|
|
406
|
-
});
|
|
407
|
-
stream.on('close', () => {
|
|
408
|
-
ptySession.active = false;
|
|
409
|
-
});
|
|
410
|
-
stream.on('error', (err) => {
|
|
411
|
-
ptySession.active = false;
|
|
412
|
-
terminal.write(`\n[PTY Error: ${err.message}]`);
|
|
413
|
-
});
|
|
414
|
-
this.ptySessions.set(ptyId, ptySession);
|
|
415
|
-
resolve(ptyId);
|
|
416
|
-
});
|
|
417
|
-
});
|
|
307
|
+
return this.ptyManager.start({
|
|
308
|
+
execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
|
|
309
|
+
}, alias, command, options);
|
|
418
310
|
}
|
|
419
|
-
/**
|
|
420
|
-
* 向 PTY 写入数据
|
|
421
|
-
*/
|
|
422
311
|
ptyWrite(ptyId, data) {
|
|
423
|
-
|
|
424
|
-
if (!ptySession) {
|
|
425
|
-
throw new Error(`PTY session '${ptyId}' not found`);
|
|
426
|
-
}
|
|
427
|
-
if (!ptySession.active) {
|
|
428
|
-
throw new Error(`PTY session '${ptyId}' is closed`);
|
|
429
|
-
}
|
|
430
|
-
return ptySession.stream.write(data);
|
|
312
|
+
return this.ptyManager.write(ptyId, data);
|
|
431
313
|
}
|
|
432
|
-
/**
|
|
433
|
-
* 读取 PTY 输出
|
|
434
|
-
* @param mode 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
|
|
435
|
-
*/
|
|
436
314
|
ptyRead(ptyId, options = {}) {
|
|
437
|
-
|
|
438
|
-
if (!ptySession) {
|
|
439
|
-
throw new Error(`PTY session '${ptyId}' not found`);
|
|
440
|
-
}
|
|
441
|
-
const mode = options.mode || 'screen';
|
|
442
|
-
const clear = options.clear !== false;
|
|
443
|
-
let data;
|
|
444
|
-
if (mode === 'screen') {
|
|
445
|
-
// 返回当前屏幕内容(解析后的纯文本)
|
|
446
|
-
data = this.getScreenContent(ptySession.terminal);
|
|
447
|
-
}
|
|
448
|
-
else {
|
|
449
|
-
// 返回原始 ANSI 流
|
|
450
|
-
data = ptySession.rawBuffer;
|
|
451
|
-
if (clear) {
|
|
452
|
-
ptySession.rawBuffer = '';
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
ptySession.lastReadAt = Date.now();
|
|
456
|
-
return {
|
|
457
|
-
data,
|
|
458
|
-
active: ptySession.active,
|
|
459
|
-
rows: ptySession.rows,
|
|
460
|
-
cols: ptySession.cols,
|
|
461
|
-
};
|
|
315
|
+
return this.ptyManager.read(ptyId, options);
|
|
462
316
|
}
|
|
463
|
-
/**
|
|
464
|
-
* 调整 PTY 窗口大小
|
|
465
|
-
*/
|
|
466
317
|
ptyResize(ptyId, rows, cols) {
|
|
467
|
-
|
|
468
|
-
if (!ptySession) {
|
|
469
|
-
throw new Error(`PTY session '${ptyId}' not found`);
|
|
470
|
-
}
|
|
471
|
-
if (!ptySession.active) {
|
|
472
|
-
throw new Error(`PTY session '${ptyId}' is closed`);
|
|
473
|
-
}
|
|
474
|
-
// 调整远程 PTY 窗口
|
|
475
|
-
ptySession.stream.setWindow(rows, cols, 0, 0);
|
|
476
|
-
// 调整本地终端仿真器
|
|
477
|
-
ptySession.terminal.resize(cols, rows);
|
|
478
|
-
ptySession.rows = rows;
|
|
479
|
-
ptySession.cols = cols;
|
|
480
|
-
return true;
|
|
318
|
+
return this.ptyManager.resize(ptyId, rows, cols);
|
|
481
319
|
}
|
|
482
|
-
/**
|
|
483
|
-
* 关闭 PTY 会话
|
|
484
|
-
*/
|
|
485
320
|
ptyClose(ptyId) {
|
|
486
|
-
|
|
487
|
-
if (!ptySession) {
|
|
488
|
-
return false;
|
|
489
|
-
}
|
|
490
|
-
try {
|
|
491
|
-
ptySession.stream.close();
|
|
492
|
-
}
|
|
493
|
-
catch {
|
|
494
|
-
}
|
|
495
|
-
try {
|
|
496
|
-
ptySession.terminal.dispose();
|
|
497
|
-
}
|
|
498
|
-
catch {
|
|
499
|
-
}
|
|
500
|
-
ptySession.active = false;
|
|
501
|
-
this.ptySessions.delete(ptyId);
|
|
502
|
-
return true;
|
|
321
|
+
return this.ptyManager.close(ptyId);
|
|
503
322
|
}
|
|
504
|
-
/**
|
|
505
|
-
* 列出所有 PTY 会话
|
|
506
|
-
*/
|
|
507
323
|
ptyList() {
|
|
508
|
-
|
|
509
|
-
for (const [id, pty] of this.ptySessions) {
|
|
510
|
-
result.push({
|
|
511
|
-
id,
|
|
512
|
-
alias: pty.alias,
|
|
513
|
-
command: pty.command,
|
|
514
|
-
rows: pty.rows,
|
|
515
|
-
cols: pty.cols,
|
|
516
|
-
createdAt: pty.createdAt,
|
|
517
|
-
lastReadAt: pty.lastReadAt,
|
|
518
|
-
bufferSize: pty.rawBuffer.length,
|
|
519
|
-
active: pty.active,
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
return result;
|
|
523
|
-
}
|
|
524
|
-
/**
|
|
525
|
-
* 关闭所有 PTY 会话
|
|
526
|
-
*/
|
|
527
|
-
ptyCloseAll() {
|
|
528
|
-
let count = 0;
|
|
529
|
-
for (const ptyId of this.ptySessions.keys()) {
|
|
530
|
-
if (this.ptyClose(ptyId)) {
|
|
531
|
-
count++;
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
return count;
|
|
324
|
+
return this.ptyManager.list();
|
|
535
325
|
}
|
|
536
|
-
|
|
537
|
-
* 创建本地端口转发
|
|
538
|
-
* 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
|
|
539
|
-
*/
|
|
326
|
+
// ===== Forward 委托 =====
|
|
540
327
|
async forwardLocal(alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
}
|
|
550
|
-
socket.pipe(stream).pipe(socket);
|
|
551
|
-
});
|
|
552
|
-
});
|
|
553
|
-
server.on('error', (err) => {
|
|
554
|
-
reject(new Error(`Local forward failed: ${err.message}`));
|
|
555
|
-
});
|
|
556
|
-
server.listen(localPort, localHost, () => {
|
|
557
|
-
const fwdSession = {
|
|
558
|
-
id: forwardId,
|
|
559
|
-
alias,
|
|
560
|
-
type: 'local',
|
|
561
|
-
localHost,
|
|
562
|
-
localPort,
|
|
563
|
-
remoteHost,
|
|
564
|
-
remotePort,
|
|
565
|
-
server,
|
|
566
|
-
createdAt: Date.now(),
|
|
567
|
-
active: true,
|
|
568
|
-
};
|
|
569
|
-
this.forwardSessions.set(forwardId, fwdSession);
|
|
570
|
-
resolve(forwardId);
|
|
571
|
-
});
|
|
328
|
+
return this.forwardManager.forwardLocal({ getClient: (a) => this.getSession(a).client }, alias, localPort, remoteHost, remotePort, localHost);
|
|
329
|
+
}
|
|
330
|
+
async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
|
|
331
|
+
return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
|
|
332
|
+
}
|
|
333
|
+
forwardClose(forwardId) {
|
|
334
|
+
return this.forwardManager.close(forwardId, {
|
|
335
|
+
getClient: (a) => this.getSession(a).client,
|
|
572
336
|
});
|
|
573
337
|
}
|
|
338
|
+
forwardList() {
|
|
339
|
+
return this.forwardManager.list();
|
|
340
|
+
}
|
|
574
341
|
/**
|
|
575
|
-
*
|
|
576
|
-
* 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
|
|
342
|
+
* 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
|
|
577
343
|
*/
|
|
578
|
-
|
|
344
|
+
execPtyStream(alias, command, options) {
|
|
579
345
|
const session = this.getSession(alias);
|
|
580
|
-
const
|
|
346
|
+
const fullCommand = this.buildCommand(command, session, { env: options.env, cwd: options.cwd });
|
|
581
347
|
return new Promise((resolve, reject) => {
|
|
582
|
-
session.client.
|
|
348
|
+
session.client.exec(fullCommand, {
|
|
349
|
+
pty: {
|
|
350
|
+
rows: options.rows || 24,
|
|
351
|
+
cols: options.cols || 80,
|
|
352
|
+
term: options.term || 'xterm-256color',
|
|
353
|
+
},
|
|
354
|
+
}, (err, stream) => {
|
|
583
355
|
if (err) {
|
|
584
|
-
reject(new Error(`
|
|
585
|
-
return;
|
|
356
|
+
reject(new Error(`PTY exec failed: ${err.message}`));
|
|
586
357
|
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
alias,
|
|
590
|
-
type: 'remote',
|
|
591
|
-
localHost,
|
|
592
|
-
localPort,
|
|
593
|
-
remoteHost,
|
|
594
|
-
remotePort,
|
|
595
|
-
createdAt: Date.now(),
|
|
596
|
-
active: true,
|
|
597
|
-
};
|
|
598
|
-
this.forwardSessions.set(forwardId, fwdSession);
|
|
599
|
-
// 确保该 session 有共享的 tcp dispatcher
|
|
600
|
-
this.ensureTcpDispatcher(session, alias);
|
|
601
|
-
resolve(forwardId);
|
|
602
|
-
});
|
|
603
|
-
});
|
|
604
|
-
}
|
|
605
|
-
// ========== PTY 会话管理 ==========
|
|
606
|
-
/**
|
|
607
|
-
* 关闭端口转发
|
|
608
|
-
*/
|
|
609
|
-
forwardClose(forwardId) {
|
|
610
|
-
const fwdSession = this.forwardSessions.get(forwardId);
|
|
611
|
-
if (!fwdSession) {
|
|
612
|
-
return false;
|
|
613
|
-
}
|
|
614
|
-
fwdSession.active = false;
|
|
615
|
-
if (fwdSession.type === 'local' && fwdSession.server) {
|
|
616
|
-
try {
|
|
617
|
-
fwdSession.server.close();
|
|
618
|
-
}
|
|
619
|
-
catch {
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
else if (fwdSession.type === 'remote') {
|
|
623
|
-
const session = this.sessions.get(fwdSession.alias);
|
|
624
|
-
if (session) {
|
|
625
|
-
try {
|
|
626
|
-
session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort);
|
|
627
|
-
}
|
|
628
|
-
catch {
|
|
358
|
+
else {
|
|
359
|
+
resolve(stream);
|
|
629
360
|
}
|
|
630
|
-
// 检查是否需要移除共享 dispatcher
|
|
631
|
-
this.removeTcpDispatcherIfEmpty(session, fwdSession.alias);
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
this.forwardSessions.delete(forwardId);
|
|
635
|
-
return true;
|
|
636
|
-
}
|
|
637
|
-
/**
|
|
638
|
-
* 列出所有端口转发
|
|
639
|
-
*/
|
|
640
|
-
forwardList() {
|
|
641
|
-
const result = [];
|
|
642
|
-
for (const [id, fwd] of this.forwardSessions) {
|
|
643
|
-
result.push({
|
|
644
|
-
id,
|
|
645
|
-
alias: fwd.alias,
|
|
646
|
-
type: fwd.type,
|
|
647
|
-
localHost: fwd.localHost,
|
|
648
|
-
localPort: fwd.localPort,
|
|
649
|
-
remoteHost: fwd.remoteHost,
|
|
650
|
-
remotePort: fwd.remotePort,
|
|
651
|
-
createdAt: fwd.createdAt,
|
|
652
|
-
active: fwd.active,
|
|
653
361
|
});
|
|
654
|
-
}
|
|
655
|
-
return result;
|
|
362
|
+
});
|
|
656
363
|
}
|
|
657
364
|
ensurePersistDir() {
|
|
658
365
|
const dir = path.dirname(this.persistPath);
|
|
@@ -687,6 +394,50 @@ export class SessionManager {
|
|
|
687
394
|
isAlive(session) {
|
|
688
395
|
return session.connected;
|
|
689
396
|
}
|
|
397
|
+
/**
|
|
398
|
+
* 调度自动重连(支持多次重试)
|
|
399
|
+
*/
|
|
400
|
+
scheduleReconnect(alias) {
|
|
401
|
+
const session = this.sessions.get(alias);
|
|
402
|
+
if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
session.reconnectAttempts++;
|
|
406
|
+
const attempt = session.reconnectAttempts;
|
|
407
|
+
setTimeout(async () => {
|
|
408
|
+
try {
|
|
409
|
+
await this.reconnect(alias);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
|
|
413
|
+
// reconnect 失败后继续调度下一次尝试
|
|
414
|
+
this.scheduleReconnect(alias);
|
|
415
|
+
}
|
|
416
|
+
}, this.reconnectDelay);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* 根据错误类型生成排查建议
|
|
420
|
+
*/
|
|
421
|
+
diagnoseConnectionError(err) {
|
|
422
|
+
const msg = err.message || '';
|
|
423
|
+
const code = err.code || '';
|
|
424
|
+
if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
|
|
425
|
+
return 'check if SSH service is running on the target host';
|
|
426
|
+
}
|
|
427
|
+
if (code === 'ETIMEDOUT' || msg.includes('ETIMEDOUT') || msg.includes('Timed out')) {
|
|
428
|
+
return 'check host reachability, firewall rules, or try a jump host';
|
|
429
|
+
}
|
|
430
|
+
if (code === 'ENOTFOUND' || msg.includes('ENOTFOUND') || msg.includes('getaddrinfo')) {
|
|
431
|
+
return 'hostname cannot be resolved, check DNS or use IP address';
|
|
432
|
+
}
|
|
433
|
+
if (msg.includes('All configured authentication methods failed')) {
|
|
434
|
+
return 'check password, key path, or key permissions (chmod 600)';
|
|
435
|
+
}
|
|
436
|
+
if (msg.includes('ECONNRESET') || msg.includes('Connection reset')) {
|
|
437
|
+
return 'connection was reset by the remote host';
|
|
438
|
+
}
|
|
439
|
+
return '';
|
|
440
|
+
}
|
|
690
441
|
/**
|
|
691
442
|
* 转义 shell 参数(使用单引号方式)
|
|
692
443
|
*/
|
|
@@ -705,7 +456,26 @@ export class SessionManager {
|
|
|
705
456
|
isValidEnvKey(key) {
|
|
706
457
|
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key);
|
|
707
458
|
}
|
|
708
|
-
|
|
459
|
+
/**
|
|
460
|
+
* 构建完整命令:注入环境变量 + 切换工作目录
|
|
461
|
+
*/
|
|
462
|
+
buildCommand(command, session, options) {
|
|
463
|
+
let fullCommand = command;
|
|
464
|
+
const env = { ...session.config.env, ...options.env };
|
|
465
|
+
if (Object.keys(env).length > 0) {
|
|
466
|
+
const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
|
|
467
|
+
if (validEntries.length > 0) {
|
|
468
|
+
const envStr = validEntries
|
|
469
|
+
.map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
|
|
470
|
+
.join('; ');
|
|
471
|
+
fullCommand = `${envStr}; ${command}`;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (options.cwd) {
|
|
475
|
+
fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`;
|
|
476
|
+
}
|
|
477
|
+
return fullCommand;
|
|
478
|
+
}
|
|
709
479
|
/**
|
|
710
480
|
* 根据用户 shell 类型生成加载配置文件的命令
|
|
711
481
|
* bash → .bashrc, zsh → .zshrc, 其他 → .profile
|
|
@@ -740,86 +510,6 @@ export class SessionManager {
|
|
|
740
510
|
// 忽略写入错误
|
|
741
511
|
}
|
|
742
512
|
}
|
|
743
|
-
/**
|
|
744
|
-
* 生成 PTY 会话 ID
|
|
745
|
-
*/
|
|
746
|
-
generatePtyId() {
|
|
747
|
-
return `pty_${++this.ptyIdCounter}_${Date.now()}`;
|
|
748
|
-
}
|
|
749
|
-
/**
|
|
750
|
-
* 从终端仿真器获取当前屏幕内容
|
|
751
|
-
*/
|
|
752
|
-
getScreenContent(terminal) {
|
|
753
|
-
const buffer = terminal.buffer.active;
|
|
754
|
-
const lines = [];
|
|
755
|
-
for (let i = 0; i < terminal.rows; i++) {
|
|
756
|
-
const line = buffer.getLine(i);
|
|
757
|
-
if (line) {
|
|
758
|
-
lines.push(line.translateToString(true));
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
// 移除尾部空行
|
|
762
|
-
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
|
|
763
|
-
lines.pop();
|
|
764
|
-
}
|
|
765
|
-
return lines.join('\n');
|
|
766
|
-
}
|
|
767
|
-
/**
|
|
768
|
-
* 生成端口转发 ID
|
|
769
|
-
*/
|
|
770
|
-
generateForwardId() {
|
|
771
|
-
return `fwd_${++this.forwardIdCounter}_${Date.now()}`;
|
|
772
|
-
}
|
|
773
|
-
/**
|
|
774
|
-
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
775
|
-
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
776
|
-
* @param alias - session 的 map key
|
|
777
|
-
*/
|
|
778
|
-
ensureTcpDispatcher(session, alias) {
|
|
779
|
-
if (session.tcpDispatcher) {
|
|
780
|
-
return; // 已存在
|
|
781
|
-
}
|
|
782
|
-
const dispatcher = (info, accept, rejectConn) => {
|
|
783
|
-
// 查找匹配的 remote forward
|
|
784
|
-
for (const fwd of this.forwardSessions.values()) {
|
|
785
|
-
if (fwd.type === 'remote' &&
|
|
786
|
-
fwd.active &&
|
|
787
|
-
fwd.alias === alias &&
|
|
788
|
-
fwd.remoteHost === info.destIP &&
|
|
789
|
-
fwd.remotePort === info.destPort) {
|
|
790
|
-
// 找到匹配的 forward,建立连接
|
|
791
|
-
const stream = accept();
|
|
792
|
-
const socket = net.createConnection(fwd.localPort, fwd.localHost);
|
|
793
|
-
socket.pipe(stream).pipe(socket);
|
|
794
|
-
socket.on('error', () => stream.close());
|
|
795
|
-
stream.on('error', () => socket.destroy());
|
|
796
|
-
return;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
// 没有匹配的 forward,拒绝连接
|
|
800
|
-
rejectConn();
|
|
801
|
-
};
|
|
802
|
-
session.tcpDispatcher = dispatcher;
|
|
803
|
-
session.client.on('tcp connection', dispatcher);
|
|
804
|
-
}
|
|
805
|
-
/**
|
|
806
|
-
* 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
|
|
807
|
-
* @param alias - session 的 map key
|
|
808
|
-
*/
|
|
809
|
-
removeTcpDispatcherIfEmpty(session, alias) {
|
|
810
|
-
if (!session.tcpDispatcher) {
|
|
811
|
-
return;
|
|
812
|
-
}
|
|
813
|
-
// 检查是否还有该 session 的 remote forward
|
|
814
|
-
for (const fwd of this.forwardSessions.values()) {
|
|
815
|
-
if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
|
|
816
|
-
return; // 还有活跃的 remote forward
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
// 没有了,移除 dispatcher
|
|
820
|
-
session.client.removeListener('tcp connection', session.tcpDispatcher);
|
|
821
|
-
session.tcpDispatcher = undefined;
|
|
822
|
-
}
|
|
823
513
|
}
|
|
824
514
|
// 全局单例
|
|
825
515
|
export const sessionManager = new SessionManager();
|