-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
110 lines (90 loc) · 2.38 KB
/
server.js
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
const express = require("express");
const path = require("path");
const http = require("http");
const SSHClient = require("ssh2").Client;
const utf8 = require("utf8");
const app = express();
const serverPort = 3000;
const server = http.createServer(app);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.render("index");
});
server.listen(serverPort, () => {
console.log(`Server running on port ${serverPort}`);
});
const createConnection = (socket, host, port, username, password) => {
ssh = new SSHClient();
ssh
.on("ready", () => {
socket.emit("data", "\r\n--- CONNECTED TO SSH SERVER, WELCOME ---\r\n");
socket.emit("status", { host, port, username });
ssh.shell((err, stream) => {
if (err) {
return socket.emit(
"data",
`\r\n--- SSH SHELL ERROR: ${err.message} ---\r\n`
);
}
socket.on("data", (data) => {
stream.write(data);
});
stream
.on("data", (d) => {
socket.emit("data", utf8.decode(d.toString("binary")));
})
.on("close", () => {
ssh.destroy();
});
});
})
.on("close", () => {
socket.emit("data", "\r\n--- SSH CONNECTION CLOSED ---\r\n");
})
.on("error", (err) => {
console.error(err);
socket.emit(
"data",
`\r\n--- SSH CONNECTION ERROR: ${err.message} ---\r\n`
);
});
return ssh;
};
let host, port, username, password;
const io = require("socket.io")(server);
io.on("connection", (socket) => {
let ssh = new SSHClient();
socket.on("close", () => {
ssh.destroy();
});
socket.on("reconnect", () => {
if (host && port && username) {
ssh.destroy();
ssh = createConnection(socket, host, port, username, password);
ssh.connect({
host,
port,
username,
password,
});
}
});
socket.on("new-connect", (data) => {
host = data.host;
port = Number(data.port);
username = data.username;
password = data.password;
if (host && port && username) {
ssh.destroy();
ssh = createConnection(socket, host, port, username, password);
ssh.connect({
host,
port,
username,
password,
});
}
});
});