· 2 分钟阅读时长 · 365 字 · -阅读 -评论

title: “An Introduction to the ssh2 Package” tags:

  • WebShell
  • Node.js slug: 9b9baeb0 date: 2024-01-14 10:31:13 summary: “A practical overview of the ssh2 package for Node.js, including common usage patterns (Client, shell/exec, HTTP agent, SFTP, Server), channel concepts, and references.”

When building a WebShell, the ssh2 package often comes in handy. Here’s a brief guide to using it.

Note: The ssh2 module is a Node.js client implementation of the OpenSSH protocol.

Common APIs

  1. Client

    1. connect — establish a connection

    Supports password/key/keyboard-interactive auth. Once connected, you can perform basic operations.

    If connection fails, enable debug logs to troubleshoot. In general, if your local terminal can connect, ssh2 can as well—they are both OpenSSH clients.

    1. con.shell

    Open an interactive shell, just like a normal terminal session with continuous input/output. You can disconnect in various ways (disconnect, idle timeout, typing exit, etc.).

    1. con.exec

    Execute a single command (e.g., cd). After execution completes, the stream ends (stream.end).

  2. httpAgent

    The agent enables tunneling into internal networks. For example, if the target machine hosts a web service on 127.0.0.1:80, you can reach it through an SSH-established agent.

  3. sftp

    For file operations, I recommend the ssh2-sftp-client package built on top of ssh2.

  4. Server

    Create an SSH server.

When using ssh2, you’ll come across the concept of Channels — here’s a note on that.

Channel

A connect call establishes a single SSH connection, which runs over TCP. Since TCP supports multiplexing, ssh2 can run different operations over the same SSH connection.

Interactive shell, SFTP, and exec commands each open a separate channel; they are isolated from one another. For example, if you sudo in an interactive shell, SFTP/exec channels are unaware. You can choose to reuse one SSH connection (multiple channels) or not — using different Client instances creates separate connections.

On the target machine, you can check SSH connection counts with netstat -an | grep ':22'.

Some Questions

Is cwd controllable?

OpenSSH does not support this, so ssh2 doesn’t either. You cannot open a .shell session in a specified CWD directly. The only workaround is to send stream.write(\cd /var/www\n`)` after starting the shell.

The downside is that your input will be echoed.

Final Thoughts

That’s it for the ssh2 basics.

References

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源