-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.ts
120 lines (112 loc) · 2.62 KB
/
ssh.ts
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
import { ConnectConfig, isConnectPasswordConfig } from "./connect.ts";
export type ExecOptions = {
extraArgs?: string[];
controlPersist?: number;
};
export type ExecResult = {
status: Deno.ProcessStatus;
stdout: Uint8Array;
stderr: Uint8Array;
};
export type ShellOptions = {
extraArgs?: string[];
controlPersist?: number;
};
export type ShellResult = Deno.Process<
Deno.RunOptions & {
stdin: "piped";
stdout: "piped";
stderr: "piped";
}
>;
export class Ssh {
constructor(public readonly config: ConnectConfig) {}
async exec(command: string, options: ExecOptions = {}): Promise<ExecResult> {
const [cmd, pass] = buildCmd(this.config);
const proc = Deno.run({
cmd: [
...cmd,
"-T",
"-o",
`ControlPath=~/.ssh/mux-${Deno.pid}`,
"-o",
"ControlMaster=auto",
"-o",
`ControlPersist=${options.controlPersist ?? 60}`,
...(options.extraArgs ?? []),
command,
],
stdin: "null",
stdout: "piped",
stderr: "piped",
env: {
...(pass ? { SSHPASS: pass } : {}),
},
});
const [status, stdout, stderr] = await Promise.all([
proc.status(),
proc.output(),
proc.stderrOutput(),
]);
proc.close();
return {
status,
stdout,
stderr,
};
}
shell(options: ShellOptions = {}): ShellResult {
const [cmd, pass] = buildCmd(this.config);
const proc = Deno.run({
cmd: [
...cmd,
"-tt",
"-o",
`ControlPath=~/.ssh/mux-${Deno.pid}`,
"-o",
"ControlMaster=auto",
"-o",
`ControlPersist=${options.controlPersist ?? 60}`,
...(options.extraArgs ?? []),
"/bin/sh",
],
stdin: "piped",
stdout: "piped",
stderr: "piped",
env: {
...(pass ? { SSHPASS: pass } : {}),
},
});
return proc;
}
}
export function buildCmd(
config: ConnectConfig,
): [string[], string | undefined] {
const suffix = [
...(config.username ? ["-l", config.username] : []),
...(config.port ? ["-p", config.port.toString()] : []),
config.host,
];
if (isConnectPasswordConfig(config)) {
const cmd = ["sshpass", "-e", "ssh", ...suffix];
return [cmd, config.password];
} else {
if (config.passphrase) {
const cmd = [
"sshpass",
"-e",
"-P",
"Enter passphrase for key",
"ssh",
"-i",
config.privateKey,
...suffix,
];
return [cmd, config.passphrase];
} else {
const cmd = ["ssh", "-i", config.privateKey, ...suffix];
return [cmd, undefined];
}
}
}