or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-ssh2

SSH2 client and server modules written in pure JavaScript for node.js

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/ssh2@1.17.x

To install, run

npx @tessl/cli install tessl/npm-ssh2@1.17.0

0

# SSH2

1

2

SSH2 is a comprehensive SSH implementation providing both client and server functionality written in pure JavaScript for Node.js. It offers complete SSH protocol support including authentication methods, command execution, shell access, SFTP file operations, port forwarding, X11 forwarding, and SSH agent integration.

3

4

## Package Information

5

6

- **Package Name**: ssh2

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install ssh2`

10

11

## Core Imports

12

13

```javascript

14

const { Client, Server } = require('ssh2');

15

```

16

17

For ES modules:

18

19

```javascript

20

import { Client, Server } from 'ssh2';

21

```

22

23

Import specific components:

24

25

```javascript

26

const {

27

Client,

28

Server,

29

utils,

30

HTTPAgent,

31

HTTPSAgent

32

} = require('ssh2');

33

```

34

35

## Basic Usage

36

37

### SSH Client

38

39

```javascript

40

const { Client } = require('ssh2');

41

42

const conn = new Client();

43

conn.on('ready', () => {

44

console.log('Client :: ready');

45

// Execute a command

46

conn.exec('uptime', (err, stream) => {

47

if (err) throw err;

48

stream.on('close', (code, signal) => {

49

console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);

50

conn.end();

51

}).on('data', (data) => {

52

console.log('STDOUT: ' + data);

53

}).stderr.on('data', (data) => {

54

console.log('STDERR: ' + data);

55

});

56

});

57

}).connect({

58

host: '192.168.100.100',

59

username: 'frylock',

60

privateKey: require('fs').readFileSync('/path/to/my/key')

61

});

62

```

63

64

### SSH Server

65

66

```javascript

67

const { Server } = require('ssh2');

68

69

new Server({

70

hostKeys: [hostKey]

71

}, (client) => {

72

console.log('Client connected!');

73

74

client.on('authentication', (ctx) => {

75

if (ctx.method === 'password' && ctx.username === 'foo' && ctx.password === 'bar') {

76

ctx.accept();

77

} else {

78

ctx.reject();

79

}

80

}).on('ready', () => {

81

console.log('Client authenticated!');

82

});

83

}).listen(0, '127.0.0.1', function() {

84

console.log('Listening on port ' + this.address().port);

85

});

86

```

87

88

## Architecture

89

90

SSH2 is organized around several key components:

91

92

- **Client**: Full-featured SSH client for connecting to remote servers

93

- **Server**: Complete SSH server implementation for hosting SSH services

94

- **SFTP**: File transfer protocol implementation supporting both client and server modes

95

- **Agents**: SSH agent integration supporting OpenSSH, Pageant, and Cygwin agents

96

- **HTTP Agents**: HTTP/HTTPS tunneling capabilities over SSH connections

97

- **Authentication**: Comprehensive authentication context system for servers

98

- **Protocol Layer**: Low-level SSH protocol implementation with encryption and key exchange

99

100

## Capabilities

101

102

### SSH Client Operations

103

104

Complete SSH client functionality including connection management, authentication, and remote operations.

105

106

```javascript { .api }

107

class Client extends EventEmitter {

108

connect(config: ClientConfig): Client;

109

end(): Client;

110

destroy(): Client;

111

exec(command: string, options: ExecOptions, callback: ExecCallback): boolean;

112

shell(windowOptions: WindowOptions, options: ShellOptions, callback: ShellCallback): boolean;

113

sftp(callback: SFTPCallback): boolean;

114

}

115

116

interface ClientConfig {

117

host?: string;

118

hostname?: string;

119

port?: number;

120

localAddress?: string;

121

localPort?: number;

122

forceIPv4?: boolean;

123

forceIPv6?: boolean;

124

keepaliveInterval?: number;

125

keepaliveCountMax?: number;

126

readyTimeout?: number;

127

ident?: string;

128

username?: string;

129

password?: string;

130

privateKey?: Buffer | string;

131

passphrase?: string;

132

tryKeyboard?: boolean;

133

agent?: string | BaseAgent;

134

agentForward?: boolean;

135

allowAgentFwd?: boolean;

136

authHandler?: AuthMethod[];

137

hostVerifier?: HostVerifier;

138

algorithms?: AlgorithmList;

139

debug?: DebugFunction;

140

}

141

```

142

143

[SSH Client](./ssh-client.md)

144

145

### SSH Server Hosting

146

147

Full SSH server implementation with authentication handling and session management.

148

149

```javascript { .api }

150

class Server extends net.Server {

151

constructor(config: ServerConfig, connectionListener?: ConnectionListener);

152

}

153

154

interface ServerConfig {

155

hostKeys: Array<Buffer | string | ParsedKey>;

156

algorithms?: AlgorithmList;

157

ident?: string;

158

banner?: string;

159

greeting?: string;

160

debug?: DebugFunction;

161

keepaliveInterval?: number;

162

keepaliveCountMax?: number;

163

}

164

165

class IncomingClient extends EventEmitter {

166

authenticated: boolean;

167

noMoreSessions: boolean;

168

end(): boolean;

169

x11(originAddr: string, originPort: number, callback: X11Callback): boolean;

170

forwardOut(boundAddr: string, boundPort: number, remoteAddr: string, remotePort: number, callback: ForwardCallback): boolean;

171

}

172

```

173

174

[SSH Server](./ssh-server.md)

175

176

### SFTP File Operations

177

178

Comprehensive SFTP implementation supporting both client and server operations with OpenSSH extensions.

179

180

```javascript { .api }

181

class SFTP extends EventEmitter {

182

// File operations

183

open(path: string, flags: string | number, attrs?: Attributes, callback?: OpenCallback): boolean;

184

close(handle: Buffer, callback?: StatusCallback): boolean;

185

read(handle: Buffer, buffer: Buffer, offset: number, length: number, position: number, callback?: ReadCallback): boolean;

186

write(handle: Buffer, buffer: Buffer, offset: number, length: number, position: number, callback?: WriteCallback): boolean;

187

188

// Directory operations

189

readdir(path: string, callback?: ReaddirCallback): boolean;

190

mkdir(path: string, attrs?: Attributes, callback?: StatusCallback): boolean;

191

rmdir(path: string, callback?: StatusCallback): boolean;

192

193

// File system operations

194

stat(path: string, callback?: AttrsCallback): boolean;

195

unlink(path: string, callback?: StatusCallback): boolean;

196

rename(oldPath: string, newPath: string, callback?: StatusCallback): boolean;

197

}

198

```

199

200

[SFTP Operations](./sftp-operations.md)

201

202

### SSH Agent Integration

203

204

Support for SSH agents including OpenSSH, Windows Pageant, and Cygwin agents.

205

206

```javascript { .api }

207

class BaseAgent {

208

getIdentities(callback: IdentitiesCallback): void;

209

sign(pubKey: ParsedKey, data: Buffer, options?: SignOptions, callback: SignCallback): void;

210

}

211

212

class OpenSSHAgent extends BaseAgent {

213

constructor(socketPath?: string);

214

getStream(callback: StreamCallback): void;

215

}

216

217

function createAgent(agent: string | BaseAgent): BaseAgent;

218

```

219

220

[SSH Agents](./ssh-agents.md)

221

222

### Port Forwarding

223

224

Local and remote port forwarding capabilities including TCP and Unix domain sockets.

225

226

```javascript { .api }

227

// Client methods

228

forwardIn(bindAddr: string, bindPort: number, callback: ForwardCallback): boolean;

229

unforwardIn(bindAddr: string, bindPort: number, callback: UnforwardCallback): boolean;

230

forwardOut(srcIP: string, srcPort: number, dstIP: string, dstPort: number, callback: ChannelCallback): boolean;

231

232

// OpenSSH extensions

233

openssh_forwardInStreamLocal(socketPath: string, callback: ForwardCallback): boolean;

234

openssh_unforwardInStreamLocal(socketPath: string, callback: UnforwardCallback): boolean;

235

openssh_forwardOutStreamLocal(socketPath: string, callback: ChannelCallback): boolean;

236

```

237

238

[Port Forwarding](./port-forwarding.md)

239

240

### HTTP Tunneling

241

242

HTTP and HTTPS agents for tunneling web traffic through SSH connections.

243

244

```javascript { .api }

245

class HTTPAgent extends http.Agent {

246

constructor(connectCfg: ClientConfig, agentOptions?: http.AgentOptions);

247

createConnection(options: http.RequestOptions, callback: ConnectCallback): void;

248

}

249

250

class HTTPSAgent extends https.Agent {

251

constructor(connectCfg: ClientConfig, agentOptions?: https.AgentOptions);

252

createConnection(options: https.RequestOptions, callback: ConnectCallback): void;

253

}

254

```

255

256

[HTTP Tunneling](./http-tunneling.md)

257

258

### Key Management

259

260

SSH key parsing and generation utilities supporting RSA, ECDSA, and Ed25519 keys.

261

262

```javascript { .api }

263

// Key parsing

264

function parseKey(keyData: string | Buffer, passphrase?: string): ParsedKey | Error;

265

266

// Key generation

267

function generateKeyPair(keyType: string, options: KeyGenOptions, callback: KeyGenCallback): void;

268

function generateKeyPairSync(keyType: string, options: KeyGenOptions): KeyPair;

269

270

interface KeyGenOptions {

271

bits?: number;

272

comment?: string;

273

format?: string;

274

passphrase?: string;

275

cipher?: string;

276

rounds?: number;

277

}

278

```

279

280

[Key Management](./key-management.md)

281

282

## Types

283

284

### Core Types

285

286

```javascript { .api }

287

interface ParsedKey {

288

type: string;

289

comment?: string;

290

public: Buffer;

291

private?: Buffer;

292

getPrivatePEM(): string;

293

getPublicPEM(): string;

294

getPublicSSH(): Buffer;

295

sign(data: Buffer, hashAlgo?: string): Buffer | Error;

296

verify(data: Buffer, signature: Buffer, hashAlgo?: string): boolean | Error;

297

}

298

299

interface AlgorithmList {

300

kex?: string[];

301

cipher?: string[];

302

serverHostKey?: string[];

303

hmac?: string[];

304

compress?: string[];

305

}

306

307

interface Attributes {

308

mode?: number;

309

uid?: number;

310

gid?: number;

311

size?: number;

312

atime?: number | Date;

313

mtime?: number | Date;

314

}

315

316

interface Stats extends Attributes {

317

isFile(): boolean;

318

isDirectory(): boolean;

319

isBlockDevice(): boolean;

320

isCharacterDevice(): boolean;

321

isSymbolicLink(): boolean;

322

isFIFO(): boolean;

323

isSocket(): boolean;

324

}

325

```

326

327

### Event Types

328

329

```javascript { .api }

330

// Client events

331

interface ClientEvents {

332

'connect': () => void;

333

'ready': () => void;

334

'error': (err: Error) => void;

335

'end': () => void;

336

'close': () => void;

337

'greeting': (name: string, version: string) => void;

338

'handshake': (negotiated: NegotiatedAlgorithms) => void;

339

'banner': (message: string, language: string) => void;

340

'keyboard-interactive': (prompts: KeyboardPrompt[]) => void;

341

'change password': (message: string, language: string, callback: PasswordChangeCallback) => void;

342

'tcp connection': (details: ConnectionDetails, accept: AcceptConnection, reject: RejectConnection) => void;

343

'unix connection': (info: UnixConnectionInfo, accept: AcceptConnection, reject: RejectConnection) => void;

344

'x11': (info: X11Info, accept: AcceptConnection, reject: RejectConnection) => void;

345

}

346

347

// Server events

348

interface ServerEvents {

349

'connection': (client: IncomingClient, info: ClientInfo) => void;

350

'error': (err: Error) => void;

351

'listening': () => void;

352

'close': () => void;

353

}

354

```

355

356

## Constants

357

358

### SFTP Constants

359

360

```javascript { .api }

361

const STATUS_CODE = {

362

OK: 0,

363

EOF: 1,

364

NO_SUCH_FILE: 2,

365

PERMISSION_DENIED: 3,

366

FAILURE: 4,

367

BAD_MESSAGE: 5,

368

NO_CONNECTION: 6,

369

CONNECTION_LOST: 7,

370

OP_UNSUPPORTED: 8

371

};

372

373

const OPEN_MODE = {

374

READ: 0x00000001,

375

WRITE: 0x00000002,

376

APPEND: 0x00000004,

377

CREAT: 0x00000008,

378

TRUNC: 0x00000010,

379

EXCL: 0x00000020

380

};

381

382

// Utility functions

383

function flagsToString(flags: number): string;

384

function stringToFlags(flagsStr: string): number;

385

```

386

387

Access via:

388

389

```javascript

390

const { utils } = require('ssh2');

391

console.log(utils.sftp.STATUS_CODE.OK); // 0

392

console.log(utils.sftp.OPEN_MODE.READ); // 1

393

394

// Convert numeric flags to string representation

395

const flags = utils.sftp.OPEN_MODE.READ | utils.sftp.OPEN_MODE.WRITE;

396

console.log(utils.sftp.flagsToString(flags)); // "r+"

397

398

// Convert string flags to numeric representation

399

const numFlags = utils.sftp.stringToFlags("w");

400

console.log(numFlags); // 0x00000002

401

```