forked from tpresley/node-remote-exec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
169 lines (144 loc) · 4.27 KB
/
index.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
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
const { Client } = require("ssh2");
const fs = require("fs");
const path = require("path");
const os = require("os");
const iconv = require("iconv-lite");
// Default SSH connection options
const defaultOptions = {
port: 22,
username: "root",
privateKey: fs.readFileSync(path.resolve(os.homedir(), ".ssh", "id_rsa")),
force: false, // Flag to allow risky commands
encoding: null, // Optional encoding for stdout and stderr
};
// List of risky commands
const riskyCommands = [
"rm",
"rmdir",
"del",
"rimraf", // Common risky commands
"rm -rf",
"shutdown",
"reboot",
"mkfs",
"dd if=",
"chmod 777 /",
"chown root",
"kill -9 -1",
"mv /",
"cp /", // Linux / macOS
"del /f /s /q",
"format",
"netsh advfirewall reset",
"netsh firewall",
"erase /f",
"rd /s /q",
"taskkill /F /IM",
"reg delete",
"sc stop",
"sc delete", // Windows
];
// Function to check if a command is risky
function isCommandRisky(cmd) {
return riskyCommands.some((riskyCmd) =>
cmd.toLowerCase().includes(riskyCmd.toLowerCase())
);
}
// Filter and mark commands as risky or safe
function filterCommands(cmds, options = {}) {
return cmds.map((cmd) => ({
cmd,
isRisky: isCommandRisky(cmd) && !options.force, // Mark risky if not forced
}));
}
// Main remoteExec function
async function remoteExec(hosts, cmds, options = {}, cb = (err) => {}) {
let errorOccurred = null;
// Merge user options with default options
const mergedOptions = { ...defaultOptions, ...options };
const filteredCmds = filterCommands(cmds, mergedOptions);
for (const hostEntry of hosts) {
const host = typeof hostEntry === "string" ? hostEntry : hostEntry.host;
const serverName =
typeof hostEntry === "string" ? hostEntry : hostEntry.name || host;
//console.log(`Connecting to host: ${serverName} (${host})`);
const conn = new Client();
const hostOptions = { ...mergedOptions, host };
try {
await new Promise((resolve, reject) => {
conn.on("ready", async () => {
console.log(`Connected to ${serverName}`);
try {
await executeCommands(conn, filteredCmds, hostEntry, mergedOptions); // Pass hostEntry for dynamic encoding
//console.log(`Completed all commands on ${serverName}`);
conn.end();
resolve();
} catch (err) {
conn.end();
reject(err);
}
});
conn.on("error", (err) => {
reject(err);
});
conn.connect(hostOptions);
});
} catch (err) {
errorOccurred = errorOccurred || err;
break;
}
}
cb(errorOccurred);
}
// Function to execute commands on the remote host
function executeCommands(conn, filteredCmds, hostEntry, options) {
return new Promise((resolve, reject) => {
let currentCmdIndex = 0;
// Determine the encoding for this host
const hostEncoding = hostEntry.encoding || options.encoding; // Prioritize host-specific encoding
function runNextCommand() {
if (currentCmdIndex >= filteredCmds.length) {
resolve();
return;
}
const { cmd, isRisky } = filteredCmds[currentCmdIndex];
if (isRisky) {
console.warn(
`Skipping risky command "${cmd}" - use force:true in options to execute.`
);
currentCmdIndex++;
runNextCommand();
return;
}
console.log(`Executing command: ${cmd}`);
conn.exec(cmd, (err, stream) => {
if (err) {
reject(err);
return;
}
if (hostEncoding) {
stream.setEncoding("binary"); // Handle binary encoding if specified
}
stream.on("data", (data) => {
const output = hostEncoding
? iconv.decode(Buffer.from(data, "binary"), hostEncoding)
: data.toString();
console.log(output);
});
stream.stderr.on("data", (data) => {
const output = hostEncoding
? iconv.decode(Buffer.from(data, "binary"), hostEncoding)
: data.toString();
console.log(output);
});
stream.on("close", (code, signal) => {
currentCmdIndex++;
runNextCommand();
});
});
}
runNextCommand();
});
}
// Export the remoteExec function
module.exports = remoteExec;