-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
87 lines (84 loc) · 2.59 KB
/
Copy pathindex.mjs
File metadata and controls
87 lines (84 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Client } from 'ssh2';
import { promises as fs } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
/**
* Execute commands on a remote SSH server using private key authentication only.
* @param {Object} options
* @param {string} options.host - Hostname or IP address
* @param {number} [options.port=22] - SSH port
* @param {string} [options.username] - SSH username (defaults to current user)
* @param {string[]} options.commands - List of commands to execute
* @param {any} [options.ClientClass] - For testing/mocking only
* @returns {Promise<Array<{result: string, code: number}>>}
*/
export async function sshExec({
host,
port = 22,
username = process.env.USER || process.env.USERNAME,
commands,
ClientClass = Client,
fsLib = fs,
homedirFn = homedir,
} = {}) {
if (!host || !commands || !Array.isArray(commands)) {
throw new Error('host and commands[] are required');
}
let privateKey;
const sshDir = join(homedirFn(), '.ssh');
for (const keyFile of ['id_ed25519', 'id_rsa']) {
try {
privateKey = await fsLib.readFile(join(sshDir, keyFile), 'utf8');
break;
} catch { }
}
if (!privateKey) throw new Error('No private key found in ~/.ssh/');
return await new Promise((resolve, reject) => {
const conn = new ClientClass();
const results = [];
let i = 0;
let ended = false;
function runNext() {
if (i >= commands.length) {
conn.end();
ended = true;
return resolve(results);
}
const command = commands[i++];
let result = '';
conn.exec(command, (err, stream) => {
if (err) {
if (!ended) conn.end();
return reject(new Error(`SSH exec error: ${err.message}`));
}
stream.on('close', (code) => {
results.push({ result, code });
runNext();
}).on('data', (data) => {
result += data;
}).stderr.on('data', (data) => {
result += data;
});
});
}
conn.on('ready', runNext)
.on('error', (err) => {
if (!ended) conn.end();
if (err.level === 'client-authentication') {
reject(new Error('SSH authentication failed: ' + err.message));
} else if (err.level === 'client-timeout') {
reject(new Error('SSH connection timed out: ' + err.message));
} else {
reject(new Error('SSH connection error: ' + err.message));
}
})
.on('end', () => { ended = true; })
.on('close', () => { ended = true; })
.connect({
host,
port,
username,
privateKey,
});
});
}