浏览器中使用Shell和SSH

Gao

调研相关软件

  • node-pty
  • xterm.js
  • blessed
  • ssh2

node-pty

链接

node.js 的 forkpty(3) 绑定。这允许您使用伪终端文件描述符分叉进程。它返回允许读 取和写入的终端对象。

这对于:

  • 编写终端仿真器(例如通过 xterm.js)。
  • 让某些程序认为您是终端,例如当您需要程序向您发送控制序列时。

node-pty 支持 Linux、macOS 和 Windows。通过使用 Windows 1809+ 上的 Windows conpty API 或者旧版本中的winpty,获得 Windows 支持。

xterm.js

链接

Xterm.js 是一个在 TypeScript 中编写的前端组件,它允许应用程序在浏览器中为其用户 带来功能齐全的终端。它被流行的项目,如 VS 代码,超级和 Theia 使用。

Feature

  • Terminal apps just work: Xterm.js 可以通大多数终端 apps,比 如bashvimtmux,一起工作,这包含了 Curses-based 应用和鼠标事件支持。
  • 性能:Xterm.js 非常快速,它甚至包括了 GPU 加速渲染
  • 丰富的 unicode 支持:支持 CJK,emojis 和 IMEs
  • 自包含:没有任何依赖就可以运行
  • 无障碍:可以打开屏幕阅读器和最小对比度支持
  • 更多的:Links,therming,addons,优秀的 API 文档,等等

What xterm.js is not

  • Xterm.js is not a terminal application that you can download and use on your computer.
  • Xterm.js is not bash. Xterm.js can be connected to processes like bash and let you interact with them (provide input, receive output).

blessed

为 node.js 开发的一个带有高级终端接口的 curses-like library

ssh2

SSH2 客户端和服务器模块以纯 JavaScript 编写的运行于 node.js.

开发/测试针对 OpenSSH(当前为 7.6) 完成。

设计实现

最初设计实现是通过 websocket 服务打通浏览器到 server 之间的连接,使 用xterm.js在浏览器创建 terminal UI,并使用node-pty在 server 打开对应的 shell 来进行服务。

这样只需要使用 web 做好认证就可以处理当前的问题。

经过一番选择后,不希望直接连接服务器,所以更换了一种方式。

在 web 服务器上启动一个ss2客户端代理,接入服务后,要求用户来输入用户的 ssh 登 陆密码来进行登陆,对应服务器上需要启动 openssh-server。在浏览器启动 xterm.js 模 拟终端,之后在浏览器和服务之间创建连接隧道,让终端和 ssh2 代理通讯。

SSH2 解析

ssh2@0.8.9 └─┬ ssh2-streams@0.4.10 ├─┬ asn1@0.2.4 │ └── safer-buffer@2.1.2 ├─┬ bcrypt-pbkdf@1.0.2 │ └── tweetnacl@0.14.5 └── streamsearch@0.1.2
  • ssh2 提供 ssh Client/Server
  • ssh-streams 提供 ssh 传输流,包含加密解密和传输处理

SSH2 API

require('ssh2').Client returns a Client constructor.

require('ssh2').Server returns a Server constructor.

require('ssh2').utils returns the utility methods from ssh2-streams.

require('ssh2').HTTPAgent returns an http.Agent constructor.

require('ssh2').HTTPSAgent returns an https.Agent constructor. Its API is the same as HTTPAgent except it's for HTTPS connections.

require('ssh2').SFTP_STATUS_CODE returns the SFTPStream.STATUS_CODE from ssh2-streams.

require('ssh2').SFTP_OPEN_MODE returns the SFTPStream.OPEN_MODE from ssh2-streams.

Client

Client events

  • banner(< string >message, < string >language) - A notice was sent by the server upon connection.

  • ready() - Authentication was successful.

  • tcp connection(< object >details, < function >accept, < function >reject) - An incoming forwarded TCP connection is being requested. Calling accept accepts the connection and returns a Channel object. Calling reject rejects the connection and no further action is needed. details contains:

    • srcIP - string - The originating IP of the connection.

    • srcPort - integer - The originating port of the connection.

    • destIP - string - The remote IP the connection was received on (given in earlier call to forwardIn()).

    • destPort - integer - The remote port the connection was received on (given in earlier call to forwardIn()).

  • x11(< object >details, < function >accept, < function >reject) - An incoming X11 connection is being requested. Calling accept accepts the connection and returns a Channel object. Calling reject rejects the connection and no further action is needed. details contains:

    • srcIP - string - The originating IP of the connection.

    • srcPort - integer - The originating port of the connection.

  • keyboard-interactive(< string >name, < string >instructions, < string >instructionsLang, < array >prompts, < function >finish) - The server is asking for replies to the given prompts for keyboard-interactive user authentication. name is generally what you'd use as a window title (for GUI apps). prompts is an array of { prompt: 'Password: ', echo: false } style objects (here echo indicates whether user input should be displayed on the screen). The answers for all prompts must be provided as an array of strings and passed to finish when you are ready to continue. Note: It's possible for the server to come back and ask more questions.

  • unix connection(< object >details, < function >accept, < function >reject) - An incoming forwarded UNIX socket connection is being requested. Calling accept accepts the connection and returns a Channel object. Calling reject rejects the connection and no further action is needed. details contains:

    • socketPath - string - The originating UNIX socket path of the connection.
  • change password(< string >message, < string >language, < function >done) - If using password-based user authentication, the server has requested that the user's password be changed. Call done with the new password.

  • continue() - Emitted when more requests/data can be sent to the server (after a Client method returned false).

  • error(< Error >err) - An error occurred. A 'level' property indicates 'client-socket' for socket-level errors and 'client-ssh' for SSH disconnection messages. In the case of 'client-ssh' messages, there may be a 'description' property that provides more detail.

  • end() - The socket was disconnected.

  • close() - The socket was closed.

Client methods

  • (constructor)() - Creates and returns a new Client instance.

  • connect(< object >config) - (void) - Attempts a connection to a server using the information given in config:

    • host - string - Hostname or IP address of the server. Default: 'localhost'

    • port - integer - Port number of the server. Default: 22

    • localAddress - string - IP address of the network interface to use to connect to the server. Default: (none -- determined by OS)

    • localPort - string - The local port number to connect from. Default: (none -- determined by OS)

    • forceIPv4 - boolean - Only connect via resolved IPv4 address for host. Default: false

    • forceIPv6 - boolean - Only connect via resolved IPv6 address for host. Default: false

    • hostHash - string - Any valid hash algorithm supported by node. The host's key is hashed using this algorithm and passed to the hostVerifier function. Default: (none)

    • hostVerifier - function - Function with parameters (hashedKey[, callback]) where hashedKey is a string hex hash of the host's key for verification purposes. Return true to continue with the handshake or false to reject and disconnect, or call callback() with true or false if you need to perform asynchronous verification. Default: (auto-accept if hostVerifier is not set)

    • username - string - Username for authentication. Default: (none)

    • password - string - Password for password-based user authentication. Default: (none)

    • agent - string - Path to ssh-agent's UNIX socket for ssh-agent-based user authentication. Windows users: set to 'pageant' for authenticating with Pageant or (actual) path to a cygwin "UNIX socket." Default: (none)

    • agentForward - boolean - Set to true to use OpenSSH agent forwarding (auth-agent@openssh.com) for the life of the connection. agent must also be set to use this feature. Default: false

    • privateKey - mixed - Buffer or string that contains a private key for either key-based or hostbased user authentication (OpenSSH format). Default: (none)

    • passphrase - string - For an encrypted private key, this is the passphrase used to decrypt it. Default: (none)

    • localHostname - string - Along with localUsername and privateKey, set this to a non-empty string for hostbased user authentication. Default: (none)

    • localUsername - string - Along with localHostname and privateKey, set this to a non-empty string for hostbased user authentication. Default: (none)

    • tryKeyboard - boolean - Try keyboard-interactive user authentication if primary user authentication method fails. If you set this to true, you need to handle the keyboard-interactive event. Default: false

    • authHandler - function - Function with parameters (methodsLeft, partialSuccess, callback) where methodsLeft and partialSuccess are null on the first authentication attempt, otherwise are an array and boolean respectively. Return or call callback() with the name of the authentication method to try next (pass false to signal no more methods to try). Valid method names are: 'none', 'password', 'publickey', 'agent', 'keyboard-interactive', 'hostbased'. Default: function that follows a set method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if tryKeyboard is true) -> Hostbased

    • keepaliveInterval - integer - How often (in milliseconds) to send SSH-level keepalive packets to the server (in a similar way as OpenSSH's ServerAliveInterval config option). Set to 0 to disable. Default: 0

    • keepaliveCountMax - integer - How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection (similar to OpenSSH's ServerAliveCountMax config option). Default: 3

    • readyTimeout - integer - How long (in milliseconds) to wait for the SSH handshake to complete. Default: 20000

    • sock - ReadableStream - A ReadableStream to use for communicating with the server instead of creating and using a new TCP connection (useful for connection hopping).

    • strictVendor - boolean - Performs a strict server vendor check before sending vendor-specific requests, etc. (e.g. check for OpenSSH server when using openssh_noMoreSessions()) Default: true

    • algorithms - object - This option allows you to explicitly override the default transport layer algorithms used for the connection. Each value must be an array of valid algorithms for that category. The order of the algorithms in the arrays are important, with the most favorable being first. For a list of valid and default algorithm names, please review the documentation for the version of ssh2-streams used by this module. Valid keys:

      • kex - array - Key exchange algorithms.

      • cipher - array - Ciphers.

      • serverHostKey - array - Server host key formats.

      • hmac - array - (H)MAC algorithms.

      • compress - array - Compression algorithms.

    • compress - mixed - Set to true to enable compression if server supports it, 'force' to force compression (disconnecting if server does not support it), or false to explicitly opt out of compression all of the time. Note: this setting is overridden when explicitly setting a compression algorithm in the algorithms configuration option. Default: (only use compression if that is only what the server supports)

    • debug - function - Set this to a function that receives a single string argument to get detailed (local) debug information. Default: (none)

Default authentication method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if tryKeyboard is true) -> Hostbased

  • exec(< string >command[, < object >options], < function >callback) - boolean - Executes command on the server. Returns false if you should wait for the continue event before sending any more traffic. callback has 2 parameters: < Error >err, < Channel >stream. Valid options properties are:

    • env - object - An environment to use for the execution of the command.

    • pty - mixed - Set to true to allocate a pseudo-tty with defaults, or an object containing specific pseudo-tty settings (see 'Pseudo-TTY settings'). Setting up a pseudo-tty can be useful when working with remote processes that expect input from an actual terminal (e.g. sudo's password prompt).

    • x11 - mixed - Set to true to use defaults below, set to a number to specify a specific screen number, or an object with the following valid properties:

      • single - boolean - Allow just a single connection? Default: false

      • screen - number - Screen number to use Default: 0

      • protocol - string - The authentication protocol name. Default: 'MIT-MAGIC-COOKIE-1'

      • cookie - mixed - The authentication cookie. Can be a hex string or a Buffer containing the raw cookie value (which will be converted to a hex string). Default: (random 16 byte value)

  • shell([[< mixed >window,] < object >options]< function >callback) - boolean - Starts an interactive shell session on the server, with an optional window object containing pseudo-tty settings (see 'Pseudo-TTY settings'). If window === false, then no pseudo-tty is allocated. options supports the x11 and env options as described in exec(). callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

  • forwardIn(< string >remoteAddr, < integer >remotePort, < function >callback) - boolean - Bind to remoteAddr on remotePort on the server and forward incoming TCP connections. callback has 2 parameters: < Error >err, < integer >port (port is the assigned port number if remotePort was 0). Returns false if you should wait for the continue event before sending any more traffic. Here are some special values for remoteAddr and their associated binding behaviors:

    • '' - Connections are to be accepted on all protocol families supported by the server.

    • '0.0.0.0' - Listen on all IPv4 addresses.

    • '::' - Listen on all IPv6 addresses.

    • 'localhost' - Listen on all protocol families supported by the server on loopback addresses only.

    • '127.0.0.1' and '::1' - Listen on the loopback interfaces for IPv4 and IPv6, respectively.

  • unforwardIn(< string >remoteAddr, < integer >remotePort, < function >callback) - boolean - Unbind from remoteAddr on remotePort on the server and stop forwarding incoming TCP connections. Until callback is called, more connections may still come in. callback has 1 parameter: < Error >err. Returns false if you should wait for the continue event before sending any more traffic.

  • forwardOut(< string >srcIP, < integer >srcPort, < string >dstIP, < integer >dstPort, < function >callback) - boolean - Open a connection with srcIP and srcPort as the originating address and port and dstIP and dstPort as the remote destination address and port. callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

  • sftp(< function >callback) - boolean - Starts an SFTP session. callback has 2 parameters: < Error >err, < SFTPStream >sftp. For methods available on sftp, see the SFTPStream client documentation (except read() and write() are used instead of readData() and writeData() respectively, for convenience). Returns false if you should wait for the continue event before sending any more traffic.

  • subsys(< string >subsystem, < function >callback) - boolean - Invokes subsystem on the server. callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

  • end() - (void) - Disconnects the socket.

  • openssh_noMoreSessions(< function >callback) - boolean - OpenSSH extension that sends a request to reject any new sessions (e.g. exec, shell, sftp, subsys) for this connection. callback has 1 parameter: < Error >err. Returns false if you should wait for the continue event before sending any more traffic.

  • openssh_forwardInStreamLocal(< string >socketPath, < function >callback) - boolean - OpenSSH extension that binds to a UNIX domain socket at socketPath on the server and forwards incoming connections. callback has 1 parameter: < Error >err. Returns false if you should wait for the continue event before sending any more traffic.

  • openssh_unforwardInStreamLocal(< string >socketPath, < function >callback) - boolean - OpenSSH extension that unbinds from a UNIX domain socket at socketPath on the server and stops forwarding incoming connections. callback has 1 parameter: < Error >err. Returns false if you should wait for the continue event before sending any more traffic.

  • openssh_forwardOutStreamLocal(< string >socketPath, < function >callback) - boolean - OpenSSH extension that opens a connection to a UNIX domain socket at socketPath on the server. callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

Server

Server events

  • connection(< Connection >client, < object >info) - A new client has connected. info contains the following properties:

    • ip - string - The remoteAddress of the connection.

    • family - string - The remoteFamily of the connection.

    • port - integer - The remotePort of the connection.

    • header - object - Information about the client's header:

      • identRaw - string - The raw client identification string.

      • versions - object - Various version information:

        • protocol - string - The SSH protocol version (always 1.99 or 2.0).

        • software - string - The software name and version of the client.

      • comments - string - Any text that comes after the software name/version.

    Example: the identification string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2 would be parsed as:

{ identRaw: 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2', version: { protocol: '2.0', software: 'OpenSSH_6.6.1p1' }, comments: 'Ubuntu-2ubuntu2' }

Server methods

  • (constructor)(< object >config[, < function >connectionListener]) - Creates and returns a new Server instance. Server instances also have the same methods/properties/events as net.Server. connectionListener if supplied, is added as a connection listener. Valid config properties:

    • hostKeys - array - An array of either Buffers/strings that contain host private keys or objects in the format of { key: <Buffer/string>, passphrase: <string> } for encrypted private keys. (Required) Default: (none)

    • algorithms - object - This option allows you to explicitly override the default transport layer algorithms used for incoming client connections. Each value must be an array of valid algorithms for that category. The order of the algorithms in the arrays are important, with the most favorable being first. For a list of valid and default algorithm names, please review the documentation for the version of ssh2-streams used by this module. Valid keys:

      • kex - array - Key exchange algorithms.

      • cipher - array - Ciphers.

      • serverHostKey - array - Server host key formats.

      • hmac - array - (H)MAC algorithms.

      • compress - array - Compression algorithms.

    • greeting - string - A message that is sent to clients immediately upon connection, before handshaking begins. Note: Most clients usually ignore this. Default: (none)

    • banner - string - A message that is sent to clients once, right before authentication begins. Default: (none)

    • ident - string - A custom server software name/version identifier. Default: 'ssh2js' + moduleVersion + 'srv'

    • highWaterMark - integer - This is the highWaterMark to use for the parser stream. Default: 32 * 1024

    • debug - function - Set this to a function that receives a single string argument to get detailed (local) debug information. Default: (none)

Connection events

  • authentication(< AuthContext >ctx) - The client has requested authentication. ctx.username contains the client username, ctx.method contains the requested authentication method, and ctx.accept() and ctx.reject([< Array >authMethodsLeft[, < Boolean >isPartialSuccess]]) are used to accept or reject the authentication request respectively. abort is emitted if the client aborts the authentication request. Other properties/methods available on ctx depends on the ctx.method of authentication the client has requested:

    • password:

      • password - string - This is the password sent by the client.
    • publickey:

      • key - object - Contains information about the public key sent by the client:

        • algo - string - The name of the key algorithm (e.g. ssh-rsa).

        • data - Buffer - The actual key data.

      • sigAlgo - mixed - If the value is undefined, the client is only checking the validity of the key. If the value is a string, then this contains the signature algorithm that is passed to crypto.createVerify().

      • blob - mixed - If the value is undefined, the client is only checking the validity of the key. If the value is a Buffer, then this contains the data that is passed to verifier.update().

      • signature - mixed - If the value is undefined, the client is only checking the validity of the key. If the value is a Buffer, then this contains a signature that is passed to verifier.verify().

    • keyboard-interactive:

      • submethods - array - A list of preferred authentication "sub-methods" sent by the client. This may be used to determine what (if any) prompts to send to the client.

      • prompt(< array >prompts[, < string >title[, < string

        instructions]], < function >callback) - boolean - Send prompts to the client. prompts is an array of { prompt: 'Prompt text', echo: true } objects (prompt being the prompt text and echo indicating whether the client's response to the prompt should be echoed to their display). callback is called with (err, responses), where responses is an array of string responses matching up to the prompts.

  • ready() - Emitted when the client has been successfully authenticated.

  • session(< function >accept, < function >reject) - Emitted when the client has requested a new session. Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc. accept() returns a new Session instance. reject() Returns false if you should wait for the continue event before sending any more traffic.

  • tcpip(< function >accept, < function >reject, < object >info) - Emitted when the client has requested an outbound (TCP) connection. accept() returns a new Channel instance representing the connection. reject() Returns false if you should wait for the continue event before sending any more traffic. info contains:

    • srcIP - string - Source IP address of outgoing connection.

    • srcPort - string - Source port of outgoing connection.

    • destIP - string - Destination IP address of outgoing connection.

    • destPort - string - Destination port of outgoing connection.

  • openssh.streamlocal(< function >accept, < function >reject, < object >info) - Emitted when the client has requested a connection to a UNIX domain socket. accept() returns a new Channel instance representing the connection. reject() Returns false if you should wait for the continue event before sending any more traffic. info contains:

    • socketPath - string - Destination socket path of outgoing connection.
  • request(< mixed >accept, < mixed >reject, < string >name, < object >info) - Emitted when the client has sent a global request for name (e.g. tcpip-forward or cancel-tcpip-forward). accept and reject are functions if the client requested a response. If bindPort === 0, you should pass the chosen port to accept() so that the client will know what port was bound. info contains additional details about the request:

    • tcpip-forward and cancel-tcpip-forward:

      • bindAddr - string - The IP address to start/stop binding to.

      • bindPort - integer - The port to start/stop binding to.

    • streamlocal-forward@openssh.com and cancel-streamlocal-forward@openssh.com:

      • socketPath - string - The socket path to start/stop binding to.
  • rekey() - Emitted when the client has finished rekeying (either client or server initiated).

  • continue() - Emitted when more requests/data can be sent to the client (after a Connection method returned false).

  • error(< Error >err) - An error occurred.

  • end() - The client socket disconnected.

  • close() - The client socket was closed.

Connection methods

  • end() - boolean - Closes the client connection. Returns false if you should wait for the continue event before sending any more traffic.

  • x11(< string >originAddr, < integer >originPort, < function >callback) - boolean - Alert the client of an incoming X11 client connection from originAddr on port originPort. callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

  • forwardOut(< string >boundAddr, < integer >boundPort, < string >remoteAddr, < integer >remotePort, < function >callback) - boolean - Alert the client of an incoming TCP connection on boundAddr on port boundPort from remoteAddr on port remotePort. callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

  • openssh_forwardOutStreamLocal(< string >socketPath, < function >callback) - boolean - Alert the client of an incoming UNIX domain socket connection on socketPath. callback has 2 parameters: < Error >err, < Channel >stream. Returns false if you should wait for the continue event before sending any more traffic.

  • rekey([< function >callback]) - boolean - Initiates a rekeying with the client. If callback is supplied, it is added as a one-time handler for the rekey event. Returns false if you should wait for the continue event before sending any more traffic.

Session events

  • pty(< mixed >accept, < mixed >reject, < object >info) - The client requested allocation of a pseudo-TTY for this session. accept and reject are functions if the client requested a response and return false if you should wait for the continue event before sending any more traffic. info has these properties:

    • cols - integer - The number of columns for the pseudo-TTY.

    • rows - integer - The number of rows for the pseudo-TTY.

    • width - integer - The width of the pseudo-TTY in pixels.

    • height - integer - The height of the pseudo-TTY in pixels.

    • modes - object - Contains the requested terminal modes of the pseudo-TTY keyed on the mode name with the value being the mode argument. (See the table at the end for valid names).

  • window-change(< mixed >accept, < mixed >reject, < object >info) - The client reported a change in window dimensions during this session. accept and reject are functions if the client requested a response and return false if you should wait for the continue event before sending any more traffic. info has these properties:

    • cols - integer - The new number of columns for the client window.

    • rows - integer - The new number of rows for the client window.

    • width - integer - The new width of the client window in pixels.

    • height - integer - The new height of the client window in pixels.

  • x11(< mixed >accept, < mixed >reject, < object >info) - The client requested X11 forwarding. accept and reject are functions if the client requested a response and return false if you should wait for the continue event before sending any more traffic. info has these properties:

    • single - boolean - true if only a single connection should be forwarded.

    • protocol - string - The name of the X11 authentication method used (e.g. MIT-MAGIC-COOKIE-1).

    • cookie - string - The X11 authentication cookie encoded in hexadecimal.

    • screen - integer - The screen number to forward X11 connections for.

  • env(< mixed >accept, < mixed >reject, < object >info) - The client requested an environment variable to be set for this session. accept and reject are functions if the client requested a response and return false if you should wait for the continue event before sending any more traffic. info has these properties:

    • key - string - The environment variable's name.

    • value - string - The environment variable's value.

  • signal(< mixed >accept, < mixed >reject, < object >info) - The client has sent a signal. accept and reject are functions if the client requested a response and return false if you should wait for the continue event before sending any more traffic. info has these properties:

    • name - string - The signal name (e.g. SIGUSR1).
  • auth-agent(< mixed >accept, < mixed >reject) - The client has requested incoming ssh-agent requests be forwarded to them. accept and reject are functions if the client requested a response and return false if you should wait for the continue event before sending any more traffic.

  • shell(< mixed >accept, < mixed >reject) - The client has requested an interactive shell. accept and reject are functions if the client requested a response. accept() returns a Channel for the interactive shell. reject() Returns false if you should wait for the continue event before sending any more traffic.

  • exec(< mixed >accept, < mixed >reject, < object >info) - The client has requested execution of a command string. accept and reject are functions if the client requested a response. accept() returns a Channel for the command execution. reject() Returns false if you should wait for the continue event before sending any more traffic. info has these properties:

    • command - string - The command line to be executed.
  • sftp(< mixed >accept, < mixed >reject) - The client has requested the SFTP subsystem. accept and reject are functions if the client requested a response. accept() returns an SFTPStream in server mode (see the SFTPStream documentation for details). reject() Returns false if you should wait for the continue event before sending any more traffic. info has these properties:

  • subsystem(< mixed >accept, < mixed >reject, < object >info) - The client has requested an arbitrary subsystem. accept and reject are functions if the client requested a response. accept() returns a Channel for the subsystem. reject() Returns false if you should wait for the continue event before sending any more traffic. info has these properties:

    • name - string - The name of the subsystem.
  • close() - The session was closed.

Channel

This is a normal streams2 Duplex Stream (used both by clients and servers), with the following changes:

  • A boolean property allowHalfOpen exists and behaves similarly to the property of the same name for net.Socket. When the stream's end() is called, if allowHalfOpen is true, only EOF will be sent (the server can still send data if they have not already sent EOF). The default value for this property is true.

  • A close event is emitted once the channel is completely closed on both the client and server.

  • Client-specific:

    • For exec():

      • An exit event may (the SSH2 spec says it is optional) be emitted when the process finishes. If the process finished normally, the process's return value is passed to the exit callback. If the process was interrupted by a signal, the following are passed to the exit callback: null, < string >signalName, < boolean >didCoreDump, < string >description.

      • If there was an exit event, the close event will be passed the same arguments for convenience.

      • A stderr property contains a Readable stream that represents output from stderr.

    • For shell() and exec():

      • The readable side represents stdout and the writable side represents stdin.

      • signal(< string >signalName) - boolean - Sends a POSIX signal to the current process on the server. Valid signal names are: 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'KILL', 'PIPE', 'QUIT', 'SEGV', 'TERM', 'USR1', and 'USR2'. Some server implementations may ignore this request if they do not support signals. Note: If you are trying to send SIGINT and you find signal() doesn't work, try writing '\x03' to the Channel stream instead. Returns false if you should wait for the continue event before sending any more traffic.

      • setWindow(< integer >rows, < integer >cols, < integer >height, < integer >width) - boolean - Lets the server know that the local terminal window has been resized. The meaning of these arguments are described in the 'Pseudo-TTY settings' section. Returns false if you should wait for the continue event before sending any more traffic.

  • Server-specific:

    • For exec-enabled channel instances there is an additional method available that may be called right before you close the channel. It has two different signatures:

      • exit(< integer >exitCode) - boolean - Sends an exit status code to the client. Returns false if you should wait for the continue event before sending any more traffic.

      • exit(< string >signalName[, < boolean >coreDumped[, < string

        errorMsg]]) - boolean - Sends an exit status code to the client. Returns false if you should wait for the continue event before sending any more traffic.

    • For exec and shell-enabled channel instances, channel.stderr is a writable stream.

Pseudo-TTY settings

  • rows - < integer > - Number of rows. Default: 24

  • cols - < integer > - Number of columns. Default: 80

  • height - < integer > - Height in pixels. Default: 480

  • width - < integer > - Width in pixels. Default: 640

  • term - < string > - The value to use for $TERM. Default: 'vt100'

  • modes - < object > - An object containing Terminal Modes as keys, with each value set to each mode argument. Default: null

rows and cols override width and height when rows and cols are non-zero.

Pixel dimensions refer to the drawable area of the window.

Zero dimension parameters are ignored.

Terminal modes

NameDescription
VINTRInterrupt character; 255 if none. Similarly for the other characters. Not all of these characters are supported on all systems.
VQUITThe quit character (sends SIGQUIT signal on POSIX systems).
VERASEErase the character to left of the cursor.
VKILLKill the current input line.
VEOFEnd-of-file character (sends EOF from the terminal).
VEOLEnd-of-line character in addition to carriage return and/or linefeed.
VEOL2Additional end-of-line character.
VSTARTContinues paused output (normally control-Q).
VSTOPPauses output (normally control-S).
VSUSPSuspends the current program.
VDSUSPAnother suspend character.
VREPRINTReprints the current input line.
VWERASEErases a word left of cursor.
VLNEXTEnter the next character typed literally, even if it is a special character
VFLUSHCharacter to flush output.
VSWTCHSwitch to a different shell layer.
VSTATUSPrints system status line (load, command, pid, etc).
VDISCARDToggles the flushing of terminal output.
IGNPARThe ignore parity flag. The parameter SHOULD be 0 if this flag is FALSE, and 1 if it is TRUE.
PARMRKMark parity and framing errors.
INPCKEnable checking of parity errors.
ISTRIPStrip 8th bit off characters.
INLCRMap NL into CR on input.
IGNCRIgnore CR on input.
ICRNLMap CR to NL on input.
IUCLCTranslate uppercase characters to lowercase.
IXONEnable output flow control.
IXANYAny char will restart after stop.
IXOFFEnable input flow control.
IMAXBELRing bell on input queue full.
ISIGEnable signals INTR, QUIT, [D]SUSP.
ICANONCanonicalize input lines.
XCASEEnable input and output of uppercase characters by preceding their lowercase equivalents with "".
ECHOEnable echoing.
ECHOEVisually erase chars.
ECHOKKill character discards current line.
ECHONLEcho NL even if ECHO is off.
NOFLSHDon't flush after interrupt.
TOSTOPStop background jobs from output.
IEXTENEnable extensions.
ECHOCTLEcho control characters as ^(Char).
ECHOKEVisual erase for line kill.
PENDINRetype pending input.
OPOSTEnable output processing.
OLCUCConvert lowercase to uppercase.
ONLCRMap NL to CR-NL.
OCRNLTranslate carriage return to newline (output).
ONOCRTranslate newline to carriage return-newline (output).
ONLRETNewline performs a carriage return (output).
CS77 bit mode.
CS88 bit mode.
PARENBParity enable.
PARODDOdd parity, else even.
TTY_OP_ISPEEDSpecifies the input baud rate in bits per second.
TTY_OP_OSPEEDSpecifies the output baud rate in bits per second.

HTTPAgent

HTTPAgent methods

  • (constructor)(< object >sshConfig[, < object >agentConfig]) - Creates and returns a new http.Agent instance used to tunnel an HTTP connection over SSH. sshConfig is what is passed to client.connect() and agentOptions is passed to the http.Agent constructor.