Skip to content

Commit 35fddb9

Browse files
committed
feat: add SSH command execution utility
1 parent 7467685 commit 35fddb9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/utils/ssh.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const { Client } = require("ssh2");
2+
3+
export const executeSSHCommand = async (
4+
command: string,
5+
host: string,
6+
port: number,
7+
username: string,
8+
password: string
9+
): Promise<string> => {
10+
return new Promise((resolve, reject) => {
11+
const conn = new Client();
12+
conn
13+
.on("ready", () => {
14+
conn.exec(command, (err: any, stream: any) => {
15+
if (err) {
16+
conn.end();
17+
return reject(err);
18+
}
19+
20+
let stdout = "";
21+
let stderr = "";
22+
23+
stream
24+
.on("close", (code: number) => {
25+
conn.end();
26+
if (code === 0) {
27+
resolve(stdout); // Return the command output
28+
} else {
29+
reject(new Error(stderr));
30+
}
31+
})
32+
.on("data", (data: { toString: () => string }) => {
33+
stdout += data.toString();
34+
})
35+
.stderr.on("data", (data: { toString: () => string }) => {
36+
stderr += data.toString();
37+
});
38+
});
39+
})
40+
.on("error", (err: any) => {
41+
console.error("SSH Error:", err);
42+
reject(err);
43+
})
44+
.connect({
45+
host,
46+
port,
47+
username,
48+
password,
49+
});
50+
});
51+
};

0 commit comments

Comments
 (0)