-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.js
More file actions
67 lines (57 loc) · 1.36 KB
/
Copy pathssh.js
File metadata and controls
67 lines (57 loc) · 1.36 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
const {Client} = require('ssh2')
class ServerConnection {
constructor(host, port, username, key) {
this.host = host
this.port = port
this.username = username
this.key = key
}
}
const runCommands = (sshConnection, commands) => {
return new Promise((resolve, reject) => {
const conn = new Client()
conn.on('ready', async () => {
let outputs = []
try {
for (let cmd of commands) {
outputs.push((await executeCommand(conn, cmd)).trim())
}
conn.end()
return resolve(outputs)
} catch (e) {
conn.end()
return reject(e)
}
})
conn.connect({
host: sshConnection.host,
port: parseInt(sshConnection.port),
username: sshConnection.username,
privateKey: sshConnection.key
})
})
}
function executeCommand(conn, cmd) {
return new Promise((resolve, reject) => {
let output = ''
conn.exec(cmd, (err, stream) => {
if (err) return reject(err)
stream.on('data', (data) => {
output += data
}).stderr.on('data', (data) => {
output += data
})
stream.on('close', (code, signal) => {
if(code === 0) {
return resolve(output.toString())
} else {
return reject(output.toString())
}
})
})
})
}
module.exports = {
ServerConnection,
runCommands
}