-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.js
More file actions
89 lines (76 loc) · 2.23 KB
/
ssh.js
File metadata and controls
89 lines (76 loc) · 2.23 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
const readline = require('readline');
const { Client } = require('ssh2');
const {
downloadFile,
uploadFile,
handleSIGINT,
createLocalTunnel,
} = require('./services');
const { completer } = require('./utils');
const config = require('./config');
const conn = new Client();
conn.on('ready', () => {
if (process.argv[2] === '-L') {
const args = process.argv[3].split(':');
if (args.length !== 3) {
throw Error('Please use correct notation for ssh forwarding');
}
const fromPort = args[0];
const toPort = args[2];
const remoteHost = args[1];
// Very basic validation
if (!fromPort || isNaN(fromPort) || !toPort || isNaN(toPort)) {
throw Error('Please provide valid port numbers');
}
if (
remoteHost.split('.').length !== 4
|| remoteHost.split('.').some(n => !n || isNaN(n) || parseInt(n) > 255 || parseInt(n) < 0)
) {
throw Error('Please provide valid remote host address');
}
createLocalTunnel(conn, fromPort, remoteHost, toPort);
} else {
conn.shell((err, stream) => {
if (err) throw err;
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
preserveCursor: true,
completer: completer,
});
stream.on('close', () => {
console.log('Connection closed.');
conn.end();
process.exit(0);
}).on('data', data => {
// setPrompt disables default behavior of readline.
rl.setPrompt('' + data);
process.stdin.pause();
process.stdout.write(data);
process.stdin.resume();
}).stderr.on('data', data => {
process.stderr.write(data);
});
rl.on('line', line => {
const trimmedLine = line.trim();
const args = trimmedLine.split(' ');
switch (args[0]) {
// Not the best solution.
case 'get':
downloadFile(stream, conn, args, config.host);
break;
case 'put':
uploadFile(stream, conn, args, config.host);
break;
default:
stream.write(line.trim() + '\n');
break;
}
});
rl.on('SIGINT', () => {
handleSIGINT(conn);
});
});
}
})
.connect(config);