-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsshAgent.js
More file actions
267 lines (240 loc) · 7.68 KB
/
sshAgent.js
File metadata and controls
267 lines (240 loc) · 7.68 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import { Client } from 'ssh2';
import { getServerConfig } from './sshConfig.js';
/**
* Agente SSH per connessioni e comandi remoti
*/
class SSHAgent {
constructor(config = {}) {
this.defaultConfig = {
readyTimeout: 20000,
keepaliveInterval: 10000,
keepaliveCountMax: 3,
...config,
};
}
/**
* Connetti a un host via SSH
* @param {Object} options - Opzioni di connessione
* @param {string} options.host - Indirizzo IP o hostname
* @param {number} options.port - Porta SSH (default: 22)
* @param {string} options.username - Username
* @param {string} options.password - Password (opzionale se si usa key)
* @param {string} options.privateKey - Chiave privata SSH (opzionale)
* @param {string} options.passphrase - Passphrase per la chiave (opzionale)
* @returns {Promise<Client>} Client SSH connesso
*/
async connect(options) {
return new Promise((resolve, reject) => {
const conn = new Client();
const config = {
host: options.host,
port: options.port || 22,
username: options.username,
...this.defaultConfig,
};
if (options.password) {
config.password = options.password;
}
if (options.privateKey) {
config.privateKey = options.privateKey;
if (options.passphrase) {
config.passphrase = options.passphrase;
}
}
conn.on('ready', () => {
resolve(conn);
});
conn.on('error', (err) => {
reject(err);
});
conn.connect(config);
});
}
/**
* Esegui un comando remoto via SSH
* @param {Object} connectionOptions - Opzioni di connessione (host, port, username, password/key)
* @param {string} command - Comando da eseguire
* @param {Object} execOptions - Opzioni per l'esecuzione (timeout, etc.)
* @returns {Promise<Object>} Risultato con stdout, stderr, code
*/
async executeCommand(connectionOptions, command, execOptions = {}) {
let conn = null;
try {
conn = await this.connect(connectionOptions);
return await this._execOnConnection(conn, command, execOptions);
} finally {
if (conn) {
conn.end();
}
}
}
/**
* Esegui un comando su una connessione già stabilita
* @private
*/
async _execOnConnection(conn, command, execOptions = {}) {
return new Promise((resolve, reject) => {
const timeout = execOptions.timeout || 30000;
let timeoutId = null;
conn.exec(command, (err, stream) => {
if (err) {
if (timeoutId) clearTimeout(timeoutId);
return reject(err);
}
let stdout = '';
let stderr = '';
stream.on('close', (code, signal) => {
if (timeoutId) clearTimeout(timeoutId);
resolve({
stdout,
stderr,
code,
signal,
success: code === 0,
});
});
stream.on('data', (data) => {
stdout += data.toString();
});
stream.stderr.on('data', (data) => {
stderr += data.toString();
});
if (timeout > 0) {
timeoutId = setTimeout(() => {
stream.destroy();
reject(new Error(`Comando timeout dopo ${timeout}ms`));
}, timeout);
}
});
});
}
/**
* Esegui più comandi in sequenza sulla stessa connessione
* @param {Object} connectionOptions - Opzioni di connessione
* @param {string[]} commands - Array di comandi da eseguire
* @param {Object} execOptions - Opzioni per l'esecuzione
* @returns {Promise<Array>} Array di risultati
*/
async executeCommands(connectionOptions, commands, execOptions = {}) {
let conn = null;
const results = [];
try {
conn = await this.connect(connectionOptions);
for (const cmd of commands) {
const result = await this._execOnConnection(conn, cmd, execOptions);
results.push({ command: cmd, ...result });
// Se un comando fallisce, interrompi la sequenza (opzionale)
if (execOptions.stopOnError && !result.success) {
break;
}
}
return results;
} finally {
if (conn) {
conn.end();
}
}
}
/**
* Testa la connettività SSH senza eseguire comandi
* @param {Object} connectionOptions - Opzioni di connessione
* @returns {Promise<boolean>} true se la connessione riesce
*/
async testConnection(connectionOptions) {
try {
const conn = await this.connect(connectionOptions);
conn.end();
return true;
} catch (err) {
return false;
}
}
/**
* Ottieni informazioni sul sistema remoto
* @param {Object} connectionOptions - Opzioni di connessione
* @returns {Promise<Object>} Informazioni sul sistema
*/
async getSystemInfo(connectionOptions) {
const commands = [
'uname -a',
'hostname',
'uptime',
'cat /etc/os-release 2>/dev/null || cat /etc/redhat-release 2>/dev/null || echo "OS info not available"',
];
const results = await this.executeCommands(connectionOptions, commands, {
timeout: 10000,
stopOnError: false,
});
return {
uname: results[0]?.stdout?.trim() || '',
hostname: results[1]?.stdout?.trim() || '',
uptime: results[2]?.stdout?.trim() || '',
osInfo: results[3]?.stdout?.trim() || '',
};
}
/**
* Connetti a un server predefinito per nome
* @param {string} serverName - Nome del server (twiky o ndei)
* @returns {Promise<Client>} Client SSH connesso
*/
async connectToServer(serverName) {
const config = getServerConfig(serverName);
if (!config) {
throw new Error(`Server "${serverName}" non trovato nella configurazione`);
}
return this.connect(config);
}
/**
* Esegui un comando su un server predefinito
* @param {string} serverName - Nome del server (twiky o ndei)
* @param {string} command - Comando da eseguire
* @param {Object} execOptions - Opzioni per l'esecuzione
* @returns {Promise<Object>} Risultato con stdout, stderr, code
*/
async executeOnServer(serverName, command, execOptions = {}) {
const config = getServerConfig(serverName);
if (!config) {
throw new Error(`Server "${serverName}" non trovato nella configurazione`);
}
return this.executeCommand(config, command, execOptions);
}
/**
* Esegui più comandi su un server predefinito
* @param {string} serverName - Nome del server (twiky o ndei)
* @param {string[]} commands - Array di comandi da eseguire
* @param {Object} execOptions - Opzioni per l'esecuzione
* @returns {Promise<Array>} Array di risultati
*/
async executeCommandsOnServer(serverName, commands, execOptions = {}) {
const config = getServerConfig(serverName);
if (!config) {
throw new Error(`Server "${serverName}" non trovato nella configurazione`);
}
return this.executeCommands(config, commands, execOptions);
}
/**
* Testa la connessione a un server predefinito
* @param {string} serverName - Nome del server (twiky o ndei)
* @returns {Promise<boolean>} true se la connessione riesce
*/
async testServerConnection(serverName) {
const config = getServerConfig(serverName);
if (!config) {
return false;
}
return this.testConnection(config);
}
/**
* Ottieni informazioni sul sistema di un server predefinito
* @param {string} serverName - Nome del server (twiky o ndei)
* @returns {Promise<Object>} Informazioni sul sistema
*/
async getServerSystemInfo(serverName) {
const config = getServerConfig(serverName);
if (!config) {
throw new Error(`Server "${serverName}" non trovato nella configurazione`);
}
return this.getSystemInfo(config);
}
}
export default SSHAgent;