Complete API reference for libssh2.js
Initialize the libssh2 library.
Parameters:
wasmModule(Object): The compiled WASM module
Returns: Promise<LibSSH2> - Initialized library instance
Example:
const ssh2 = await init(wasmModule);Create a new SSH session.
Parameters:
socket(WebSocket | Socket): WebSocket or Node.js Socket objectoptions(Object, optional):onerror(Function): Error callback(err: number, msg: string) => voidonclose(Function): Close callback(err: number, socket: any) => void
Returns: Session - SSH session object
Example:
const session = ssh2.createSession(ws, {
onerror: (err, msg) => console.error(msg),
onclose: () => console.log('Closed')
});Authenticate with username and password.
Parameters:
username(string): Usernamepassword(string): Password
Returns: Promise<void>
Example:
await session.login('user', 'password');Create a new command channel.
Returns: Promise<Channel>
Example:
const channel = await session.CHANNEL();Create SFTP subsystem.
Returns: Promise<SFTP>
Example:
const sftp = await session.SFTP();Create TCP port forwarding channel.
Parameters:
host(string): Remote hostport(number): Remote port
Returns: Promise<Channel>
Example:
const tcpChannel = await session.TCPIP('localhost', 3000);Get server's host key fingerprint.
Returns: string - SHA1 fingerprint in hex format
Example:
const fp = session.fingerprint();
console.log('Fingerprint:', fp);Close the SSH session and underlying socket.
Returns: void
Execute a command on the remote server.
Parameters:
command(string): Command to execute
Returns: Promise<void>
Example:
await channel.exec('ls -la');
const output = await channel.read();Start an interactive shell.
Returns: Promise<void>
Example:
await channel.shell();
channel.onmessage = (err, data) => console.log(data);
await channel.write('ls\n');Read output from channel.
Returns: Promise<string> - Channel output
Example:
const output = await channel.read();Read error output (stderr) from channel.
Returns: Promise<string> - Error output
Example:
const errors = await channel.read_err();Write data to channel.
Parameters:
data(string): Data to write
Returns: Promise<number> - Bytes written
Example:
await channel.write('echo "Hello"\n');Request a pseudo-terminal.
Parameters:
term(string): Terminal type (e.g., 'xterm', 'vt100')
Returns: Promise<void>
Example:
await channel.pty('xterm-256color');Set terminal size.
Parameters:
width(number): Terminal width in charactersheight(number): Terminal height in characters
Returns: Promise<void>
Example:
await channel.pty_size(80, 24);Set environment variable.
Parameters:
name(string): Variable namevalue(string): Variable value
Returns: Promise<void>
Example:
await channel.setenv('LANG', 'en_US.UTF-8');Check if channel has reached end-of-file.
Returns: Promise<boolean>
Flush the channel.
Returns: Promise<void>
Close the channel.
Returns: Promise<void>
Called when data is received.
Type: (err: number, data: string) => void
Example:
channel.onmessage = (err, data) => {
console.log('Received:', data);
};Called on error.
Type: (err: number, msg: string) => void
Called when channel closes.
Type: () => void
Open a file.
Parameters:
path(string): File pathflags(number): Open flags (see SFTP.FLAGS)mode(number): File permissions (octal)
Returns: Promise<SFTPHandle>
Example:
const file = await sftp.open(
'/remote/file.txt',
ssh2.SFTP.FLAGS.FXF_READ,
0
);Open a directory.
Parameters:
path(string): Directory path
Returns: Promise<SFTPDirHandle>
Example:
const dir = await sftp.opendir('/remote/path');Get file/directory status.
Parameters:
path(string): Path
Returns: Promise<SFTPAttributes>
Example:
const attrs = await sftp.stat('/remote/file.txt');
console.log('Size:', attrs.filesize);
console.log('Permissions:', attrs.perm.toString(8));Get file/directory status (don't follow symlinks).
Parameters:
path(string): Path
Returns: Promise<SFTPAttributes>
Create directory.
Parameters:
path(string): Directory pathmode(number): Permissions (octal)
Returns: Promise<void>
Example:
await sftp.mkdir('/remote/newdir', 0o755);Remove directory.
Parameters:
path(string): Directory path
Returns: Promise<void>
Delete file.
Parameters:
path(string): File path
Returns: Promise<void>
Example:
await sftp.unlink('/remote/file.txt');Rename/move file.
Parameters:
source(string): Source pathdest(string): Destination pathflags(number): Rename flags
Returns: Promise<void>
Example:
await sftp.rename(
'/old/path.txt',
'/new/path.txt',
ssh2.SFTP.RENAME_OVERWRITE
);Read symbolic link.
Parameters:
path(string): Symlink path
Returns: Promise<string> - Link target
Create symbolic link.
Parameters:
orig(string): Original pathdest(string): Link pathtype(number): Link type
Returns: Promise<string>
Resolve path to absolute path.
Parameters:
path(string): Path
Returns: Promise<string> - Absolute path
Get filesystem statistics.
Parameters:
path(string): Path
Returns: Promise<SFTPStatVFS>
Shutdown SFTP subsystem.
Returns: Promise<void>
Read from file.
Returns: Promise<string> - File data
Example:
const data = await handle.read();Write to file.
Parameters:
buffer(string | ArrayBuffer): Data to write
Returns: Promise<number> - Bytes written
Example:
await handle.write('Hello, World!');Seek to position.
Parameters:
offset(number): Byte offset
Returns: Promise<void>
Get current position.
Returns: Promise<number> - Current offset
Get file attributes.
Returns: Promise<SFTPAttributes>
Close file handle.
Returns: Promise<void>
Read directory entry.
Returns: Promise<string> - Filename or empty string if end
Example:
let entry;
while ((entry = await dir.readdir())) {
console.log('File:', entry);
}Close directory handle.
Returns: Promise<void>
Error codes for SSH operations.
ssh2.ERROR.NONE // 0
ssh2.ERROR.AUTHENTICATION_FAILED // -18
ssh2.ERROR.CHANNEL_UNKNOWN // -23
ssh2.ERROR.EAGAIN // -37 (try again)
// ... see full list in typesError messages mapping.
ssh2.ERRMSG['-18'] // 'AUTHENTICATION_FAILED'File open flags.
ssh2.SFTP.FLAGS.FXF_READ // Read
ssh2.SFTP.FLAGS.FXF_WRITE // Write
ssh2.SFTP.FLAGS.FXF_APPEND // Append
ssh2.SFTP.FLAGS.FXF_CREAT // Create if not exists
ssh2.SFTP.FLAGS.FXF_TRUNC // Truncate
ssh2.SFTP.FLAGS.FXF_EXCL // Exclusive createFile permissions.
ssh2.SFTP.MODE.S_IRUSR // Owner read
ssh2.SFTP.MODE.S_IWUSR // Owner write
ssh2.SFTP.MODE.S_IXUSR // Owner execute
ssh2.SFTP.MODE.S_IRWXU // Owner all (0700)
ssh2.SFTP.MODE.S_IRWXG // Group all (0070)
ssh2.SFTP.MODE.S_IRWXO // Other all (0007)File types.
ssh2.SFTP.TYPE.REGULAR // Regular file
ssh2.SFTP.TYPE.DIRECTORY // Directory
ssh2.SFTP.TYPE.SYMLINK // Symbolic linktry {
await session.login(username, password);
} catch (error) {
console.error('Login failed:', ssh2.ERRMSG[error]);
}if (error === ssh2.ERROR.AUTHENTICATION_FAILED) {
console.error('Invalid credentials');
} else if (error === ssh2.ERROR.EAGAIN) {
// Retry operation
}const session = ssh2.createSession(ws, {
onerror: (err, msg) => {
if (err === ssh2.ERROR.SOCKET_DISCONNECT) {
console.error('Connection lost');
}
}
});const ssh2 = await init(wasmModule);
const ws = new WebSocket('wss://server.com');
const session = ssh2.createSession(ws);
ws.onopen = async () => {
await session.login('user', 'pass');
const channel = await session.CHANNEL();
await channel.exec('hostname');
const output = await channel.read();
console.log(output);
await channel.close();
session.close();
};const channel = await session.CHANNEL();
await channel.pty('xterm-256color');
await channel.pty_size(80, 24);
await channel.shell();
channel.onmessage = (err, data) => {
process.stdout.write(data);
};
process.stdin.on('data', async (data) => {
await channel.write(data.toString());
});const sftp = await session.SFTP();
const file = await sftp.open(
'/remote/file.txt',
ssh2.SFTP.FLAGS.FXF_WRITE | ssh2.SFTP.FLAGS.FXF_CREAT,
0o644
);
await file.write('File content here');
await file.close();const sftp = await session.SFTP();
const dir = await sftp.opendir('/path');
let entry;
while ((entry = await dir.readdir())) {
const attrs = await sftp.stat(`/path/${entry}`);
console.log(entry, attrs.filesize);
}
await dir.close();For more examples, see USAGE.md.