0
# SSH Client
1
2
Complete SSH client functionality for connecting to remote SSH servers with comprehensive authentication, command execution, shell access, and tunneling capabilities.
3
4
## Capabilities
5
6
### Client Class
7
8
Creates and manages SSH client connections with full protocol support.
9
10
```javascript { .api }
11
/**
12
* SSH client for connecting to remote servers
13
* Extends EventEmitter for connection lifecycle events
14
*/
15
class Client extends EventEmitter {
16
constructor();
17
connect(config: ClientConfig): Client;
18
end(): Client;
19
destroy(): Client;
20
setNoDelay(noDelay?: boolean): Client;
21
}
22
23
interface ClientConfig {
24
// Connection settings
25
host?: string;
26
hostname?: string;
27
port?: number;
28
localAddress?: string;
29
localPort?: number;
30
forceIPv4?: boolean;
31
forceIPv6?: boolean;
32
keepaliveInterval?: number;
33
keepaliveCountMax?: number;
34
readyTimeout?: number;
35
36
// Identification
37
ident?: string;
38
39
// Authentication
40
username?: string;
41
password?: string;
42
privateKey?: Buffer | string;
43
passphrase?: string;
44
tryKeyboard?: boolean;
45
agent?: string | BaseAgent;
46
agentForward?: boolean;
47
allowAgentFwd?: boolean;
48
authHandler?: AuthMethod[] | AuthHandlerMiddleware;
49
50
// Security
51
hostVerifier?: HostVerifier;
52
hostHash?: string;
53
strictVendor?: boolean;
54
55
// Protocol settings
56
algorithms?: AlgorithmList;
57
58
// Advanced
59
debug?: DebugFunction;
60
sock?: Duplex;
61
timeout?: number;
62
}
63
```
64
65
**Usage Examples:**
66
67
```javascript
68
const { Client } = require('ssh2');
69
70
// Basic password authentication
71
const conn = new Client();
72
conn.connect({
73
host: '192.168.1.100',
74
username: 'ubuntu',
75
password: 'mypassword'
76
});
77
78
// Key-based authentication
79
conn.connect({
80
host: 'example.com',
81
username: 'user',
82
privateKey: require('fs').readFileSync('/path/to/key'),
83
passphrase: 'keypassword'
84
});
85
86
// Agent-based authentication
87
conn.connect({
88
host: 'server.com',
89
username: 'user',
90
agent: process.env.SSH_AUTH_SOCK,
91
agentForward: true
92
});
93
```
94
95
### Command Execution
96
97
Execute commands on the remote server with comprehensive options and stream handling.
98
99
```javascript { .api }
100
/**
101
* Execute a command on the remote server
102
* @param command - Command string to execute
103
* @param options - Execution options
104
* @param callback - Callback receiving stream for command I/O
105
* @returns false if connection not ready, true otherwise
106
*/
107
exec(command: string, options?: ExecOptions, callback?: ExecCallback): boolean;
108
exec(command: string, callback: ExecCallback): boolean;
109
110
interface ExecOptions {
111
env?: { [key: string]: string };
112
pty?: boolean | PseudoTtyOptions;
113
x11?: boolean | X11Options;
114
}
115
116
interface PseudoTtyOptions {
117
rows?: number;
118
cols?: number;
119
height?: number;
120
width?: number;
121
term?: string;
122
}
123
124
interface X11Options {
125
single?: boolean;
126
screen?: number;
127
protocol?: string;
128
cookie?: string;
129
}
130
131
type ExecCallback = (err: Error | null, stream?: ClientChannel) => void;
132
```
133
134
**Usage Examples:**
135
136
```javascript
137
// Simple command execution
138
conn.exec('ls -la', (err, stream) => {
139
if (err) throw err;
140
141
stream.on('close', (code, signal) => {
142
console.log('Command finished with code:', code);
143
conn.end();
144
}).on('data', (data) => {
145
console.log('STDOUT:', data.toString());
146
}).stderr.on('data', (data) => {
147
console.log('STDERR:', data.toString());
148
});
149
});
150
151
// Command with environment variables
152
conn.exec('echo $CUSTOM_VAR', {
153
env: { CUSTOM_VAR: 'hello world' }
154
}, (err, stream) => {
155
// Handle stream...
156
});
157
158
// Command with pseudo-TTY
159
conn.exec('top', {
160
pty: {
161
rows: 24,
162
cols: 80,
163
term: 'xterm'
164
}
165
}, (err, stream) => {
166
// Handle interactive command...
167
});
168
```
169
170
### Interactive Shell
171
172
Request an interactive shell session with optional windowing and pseudo-TTY options.
173
174
```javascript { .api }
175
/**
176
* Request an interactive shell session
177
* @param window - Terminal window settings
178
* @param options - Shell options
179
* @param callback - Callback receiving shell stream
180
* @returns false if connection not ready, true otherwise
181
*/
182
shell(window?: WindowOptions, options?: ShellOptions, callback?: ShellCallback): boolean;
183
shell(options: ShellOptions, callback: ShellCallback): boolean;
184
shell(callback: ShellCallback): boolean;
185
186
interface WindowOptions {
187
rows?: number;
188
cols?: number;
189
height?: number;
190
width?: number;
191
term?: string;
192
}
193
194
interface ShellOptions {
195
env?: { [key: string]: string };
196
x11?: boolean | X11Options;
197
}
198
199
type ShellCallback = (err: Error | null, stream?: ClientChannel) => void;
200
```
201
202
**Usage Examples:**
203
204
```javascript
205
// Basic shell
206
conn.shell((err, stream) => {
207
if (err) throw err;
208
209
stream.on('close', () => {
210
console.log('Shell closed');
211
conn.end();
212
}).on('data', (data) => {
213
process.stdout.write(data);
214
});
215
216
process.stdin.pipe(stream);
217
});
218
219
// Shell with specific terminal settings
220
conn.shell({
221
rows: 30,
222
cols: 120,
223
term: 'xterm-color'
224
}, (err, stream) => {
225
// Handle shell stream...
226
});
227
```
228
229
### Subsystem Access
230
231
Access SSH subsystems like SFTP or custom subsystems.
232
233
```javascript { .api }
234
/**
235
* Request a subsystem (like SFTP)
236
* @param name - Subsystem name
237
* @param callback - Callback receiving subsystem stream
238
* @returns false if connection not ready, true otherwise
239
*/
240
subsys(name: string, callback: SubsysCallback): boolean;
241
242
type SubsysCallback = (err: Error | null, stream?: ClientChannel) => void;
243
```
244
245
### SFTP Access
246
247
Get an SFTP client instance for file operations.
248
249
```javascript { .api }
250
/**
251
* Request SFTP subsystem
252
* @param callback - Callback receiving SFTP instance
253
* @returns false if connection not ready, true otherwise
254
*/
255
sftp(callback: SFTPCallback): boolean;
256
257
type SFTPCallback = (err: Error | null, sftp?: SFTP) => void;
258
```
259
260
**Usage Example:**
261
262
```javascript
263
conn.sftp((err, sftp) => {
264
if (err) throw err;
265
266
sftp.readdir('/home/user', (err, list) => {
267
if (err) throw err;
268
console.log('Directory listing:', list);
269
conn.end();
270
});
271
});
272
```
273
274
### Port Forwarding
275
276
Set up local and remote port forwarding for tunneling connections.
277
278
```javascript { .api }
279
/**
280
* Request remote port forwarding (server binds port and forwards to client)
281
* @param bindAddr - Address to bind on remote server
282
* @param bindPort - Port to bind on remote server
283
* @param callback - Callback with forwarding result
284
* @returns false if connection not ready, true otherwise
285
*/
286
forwardIn(bindAddr: string, bindPort: number, callback: ForwardCallback): boolean;
287
288
/**
289
* Cancel remote port forwarding
290
* @param bindAddr - Address that was bound
291
* @param bindPort - Port that was bound
292
* @param callback - Callback with cancellation result
293
* @returns false if connection not ready, true otherwise
294
*/
295
unforwardIn(bindAddr: string, bindPort: number, callback: UnforwardCallback): boolean;
296
297
/**
298
* Request local port forwarding (client connects through server to destination)
299
* @param srcIP - Source IP address
300
* @param srcPort - Source port
301
* @param dstIP - Destination IP address
302
* @param dstPort - Destination port
303
* @param callback - Callback receiving connection stream
304
* @returns false if connection not ready, true otherwise
305
*/
306
forwardOut(srcIP: string, srcPort: number, dstIP: string, dstPort: number, callback: ChannelCallback): boolean;
307
308
type ForwardCallback = (err: Error | null, bindPort?: number) => void;
309
type UnforwardCallback = (err: Error | null) => void;
310
type ChannelCallback = (err: Error | null, stream?: ClientChannel) => void;
311
```
312
313
### OpenSSH Extensions
314
315
Extended functionality specific to OpenSSH servers.
316
317
```javascript { .api }
318
/**
319
* Disable new session creation (OpenSSH extension)
320
* @param callback - Callback with operation result
321
* @returns false if connection not ready, true otherwise
322
*/
323
openssh_noMoreSessions(callback: StatusCallback): boolean;
324
325
/**
326
* Request Unix domain socket forwarding (OpenSSH extension)
327
* @param socketPath - Unix socket path to bind
328
* @param callback - Callback with forwarding result
329
* @returns false if connection not ready, true otherwise
330
*/
331
openssh_forwardInStreamLocal(socketPath: string, callback: ForwardCallback): boolean;
332
333
/**
334
* Cancel Unix domain socket forwarding (OpenSSH extension)
335
* @param socketPath - Unix socket path to unbind
336
* @param callback - Callback with cancellation result
337
* @returns false if connection not ready, true otherwise
338
*/
339
openssh_unforwardInStreamLocal(socketPath: string, callback: UnforwardCallback): boolean;
340
341
/**
342
* Connect to Unix domain socket through server (OpenSSH extension)
343
* @param socketPath - Unix socket path to connect to
344
* @param callback - Callback receiving connection stream
345
* @returns false if connection not ready, true otherwise
346
*/
347
openssh_forwardOutStreamLocal(socketPath: string, callback: ChannelCallback): boolean;
348
349
type StatusCallback = (err: Error | null) => void;
350
```
351
352
## Events
353
354
### Connection Events
355
356
```javascript { .api }
357
interface ClientEvents {
358
/**
359
* Emitted when socket connection is established
360
*/
361
'connect': () => void;
362
363
/**
364
* Emitted when authentication is successful and client is ready
365
*/
366
'ready': () => void;
367
368
/**
369
* Emitted when an error occurs
370
*/
371
'error': (err: Error) => void;
372
373
/**
374
* Emitted when the client connection is ending
375
*/
376
'end': () => void;
377
378
/**
379
* Emitted when the client connection is closed
380
*/
381
'close': () => void;
382
383
/**
384
* Emitted when server identification is received
385
*/
386
'greeting': (name: string, version: string) => void;
387
388
/**
389
* Emitted when SSH handshake is completed
390
*/
391
'handshake': (negotiated: NegotiatedAlgorithms) => void;
392
}
393
```
394
395
### Authentication Events
396
397
```javascript { .api }
398
interface AuthenticationEvents {
399
/**
400
* Emitted when server sends authentication banner
401
*/
402
'banner': (message: string, language: string) => void;
403
404
/**
405
* Emitted for keyboard-interactive authentication prompts
406
*/
407
'keyboard-interactive': (
408
name: string,
409
instructions: string,
410
lang: string,
411
prompts: KeyboardPrompt[],
412
finish: KeyboardFinishCallback
413
) => void;
414
415
/**
416
* Emitted when server requests password change
417
*/
418
'change password': (
419
message: string,
420
language: string,
421
callback: PasswordChangeCallback
422
) => void;
423
}
424
```
425
426
### Connection Request Events
427
428
```javascript { .api }
429
interface ConnectionRequestEvents {
430
/**
431
* Emitted for incoming TCP connection requests (from remote forwarding)
432
*/
433
'tcp connection': (
434
details: TcpConnectionDetails,
435
accept: AcceptConnection<ClientChannel>,
436
reject: RejectConnection
437
) => void;
438
439
/**
440
* Emitted for incoming Unix connection requests (OpenSSH extension)
441
*/
442
'unix connection': (
443
info: UnixConnectionInfo,
444
accept: AcceptConnection<ClientChannel>,
445
reject: RejectConnection
446
) => void;
447
448
/**
449
* Emitted for incoming X11 connection requests
450
*/
451
'x11': (
452
info: X11Info,
453
accept: AcceptConnection<ClientChannel>,
454
reject: RejectConnection
455
) => void;
456
457
/**
458
* Emitted when server provides updated host keys
459
*/
460
'hostkeys': (keys: ParsedKey[]) => void;
461
}
462
```
463
464
## Type Definitions
465
466
### Connection and Stream Types
467
468
```javascript { .api }
469
interface ClientChannel extends Duplex {
470
stderr: Duplex;
471
setWindow(rows: number, cols: number, height?: number, width?: number): boolean;
472
signal(signalName: string): boolean;
473
exit(status: number): boolean;
474
}
475
476
interface NegotiatedAlgorithms {
477
kex: string;
478
srvHostKey: string;
479
cs: {
480
cipher: string;
481
mac: string;
482
compress: string;
483
lang: string;
484
};
485
sc: {
486
cipher: string;
487
mac: string;
488
compress: string;
489
lang: string;
490
};
491
}
492
493
interface TcpConnectionDetails {
494
srcIP: string;
495
srcPort: number;
496
destIP: string;
497
destPort: number;
498
}
499
500
interface UnixConnectionInfo {
501
socketPath: string;
502
}
503
504
interface X11Info {
505
srcIP: string;
506
srcPort: number;
507
}
508
```
509
510
### Authentication Types
511
512
```javascript { .api }
513
interface KeyboardPrompt {
514
prompt: string;
515
echo: boolean;
516
}
517
518
type KeyboardFinishCallback = (responses: string[]) => void;
519
type PasswordChangeCallback = (newPassword: string) => void;
520
521
type AcceptConnection<T = ClientChannel> = () => T;
522
type RejectConnection = () => boolean;
523
524
// Authentication methods
525
type AuthMethod =
526
| 'none'
527
| 'password'
528
| 'publickey'
529
| 'hostbased'
530
| 'keyboard-interactive';
531
532
type AuthHandlerMiddleware = (
533
methodsLeft: AuthMethod[],
534
partialSuccess: boolean,
535
callback: AuthHandlerCallback
536
) => void;
537
538
type AuthHandlerCallback = (authMethod: AuthMethod | false) => void;
539
540
type HostVerifier = (
541
hashedKey: Buffer,
542
callback: HostVerifyCallback
543
) => void;
544
545
type HostVerifyCallback = (valid: boolean) => void;
546
547
type DebugFunction = (message: string) => void;
548
```