Class SshClient
- Namespace
- SshSharp
- Assembly
- SshSharp.dll
An authenticated SSH client connection: run commands over it. Create one with ConnectAsync(Stream, SshClientOptions, bool, CancellationToken).
public sealed class SshClient : IAsyncDisposable
- Inheritance
-
SshClient
- Implements
- Inherited Members
- Extension Methods
Properties
- Algorithms
The algorithms in use: key exchange (and whether it is post-quantum, IsPostQuantum), host key signature, ciphers and MACs. A key re-exchange can change them; each read returns the current ones.
- BytesReceived
SSH message bytes received over the connection so far, counted as BytesSent is (after decryption and decompression).
- BytesSent
SSH message bytes sent over the connection so far, from the key exchange on: the payload of each packet, key exchange messages (KEXINIT, NEWKEYS, EXT_INFO) included, before compression, encryption, padding and MAC, as the
sshsharp.bytes.sentmetric counts them. Safe to read from any thread.
- ConnectedAt
When the connection was established (the moment authentication succeeded), in UTC.
- ConnectionClosed
Cancelled when the connection ends for any reason, so pending work can stop or reconnect. ConnectionError says why.
- ConnectionError
Why the connection ended (an SshException, usually), or null while it is up.
- DynamicForwardings
The
DynamicForwardSOCKS proxies started from ssh_config; disposed with the client.
- HostKey
The host key the server proved possession of.
- IsConnected
Whether the connection is still up: false once the server disconnected, the connection failed (including a missed keep-alive, see KeepAliveInterval), or the client was disposed.
- LocalEndPoint
The local address and port of the TCP connection, under the same conditions as RemoteEndPoint; null otherwise.
- LocalForwardings
The
LocalForwardforwardings started from ssh_config (StartForwardings); disposed with the client.
- LocalSocketForwardings
The
LocalForwardforwardings that listen on a Unix socket here (LocalForward /path target) started from ssh_config; disposed with the client. Those that listen on a port, to a Unix socket on the server too, are in LocalForwardings.
- RemoteEndPoint
The address and port of the server, as the TCP connection sees it, when the connection runs over a socket: a TCP connection SshSharp made (with ConnectAsync(string, int, SshClientOptions, CancellationToken), or by
ssh_configalias without a jump host or proxy command), or a NetworkStream passed to ConnectAsync(Stream, SshClientOptions, bool, CancellationToken). Through an HTTP or SOCKS proxy it is the proxy's address. Null over any other stream (a ProxyJump tunnel, a ProxyCommand, a pipe). Read once, when the connection is made. An IPv4 address is given as such, not in the IPv4-mapped IPv6 form (::ffff:192.0.2.1) a dual-mode socket reports.
- RemoteForwardings
The
RemoteForwardforwardings started from ssh_config; disposed with the client.
- RemoteSocketForwardings
The
RemoteForwardforwardings of a Unix socket on the server (RemoteForward /path target) started from ssh_config.
- ServerIdentification
The server's identification string, for example
SSH-2.0-OpenSSH_9.9.
- SessionId
The session identifier (RFC 4253 section 7.2): the exchange hash of the first key exchange, which stays the same for the connection's life, re-exchanges included. Both sides know it, and signatures made during authentication are bound to it, so it identifies this connection, for example to correlate with the server's records or to bind something of your own to it. It is not secret. This is a copy, which stays readable after the client is disposed.
Methods
- ConnectAsync(Stream, SshClientOptions, bool, CancellationToken)
Runs the SSH protocol over an existing stream (a socket, a WebSocket wrapper, a tunnel from another connection, ...).
- ConnectAsync(string, SshConfigConnectOptions?, CancellationToken)
Connects like
ssh destinationdoes:destination([user@]host, an alias, orssh://[user@]host[:port]) is resolved withssh_config, and the connection follows it: HostName, Port, User, IdentityFile keys, known_hosts with StrictHostKeyChecking, Ciphers/KexAlgorithms/HostKeyAlgorithms/MACs, ProxyJump chains, ProxyCommand, ServerAliveInterval/ServerAliveCountMax, ConnectTimeout and AddressFamily.
- ConnectAsync(string, int, SshClientOptions, CancellationToken)
Connects to
hostover TCP, performs the handshake and authenticates. ConnectTimeout bounds the whole attempt, and AddressFamily chooses which of the host's addresses are tried. With JumpHosts, the server is reached through them, andhostis resolved by the last one.
- CreateHttpConnectCallback()
A ConnectCallback that makes HttpClient's connections through this SSH connection (OpenTcpTunnelAsync(string, int, CancellationToken)), so it can reach web services only the server reaches, such as an internal API behind a bastion. Host names are resolved by the server. TLS still runs end to end, from here to the service. Set UseProxy to false: with a system proxy configured, HttpClient would otherwise connect to that proxy, through the server, instead of to the service.
- DisposeAsync()
Disconnects and releases the connection.
- ForwardDynamicPortAsync(IPEndPoint, NetworkCredential?, CancellationToken)
Dynamic port forwarding (
ssh -D) with a SOCKS proxy that requires a user name and password: SOCKS 5 username/password authentication (RFC 1929). Applications must givecredentials; SOCKS 4 and 4a, which have no passwords, and SOCKS 5 clients that do not authenticate, are refused. Use it when the proxy must listen beyond loopback (for a container, a VM or other machines). The credentials only keep out those who do not know them: RFC 1929 sends them in clear text, and the application's traffic to the proxy is not encrypted either (only the hop from the server on is), so anyone who can watch the local network can read and reuse them. Prefer a loopback address whenever the applications run on this machine. Without credentials (null), the same as ForwardDynamicPortAsync(IPEndPoint, CancellationToken).
- ForwardDynamicPortAsync(IPEndPoint, CancellationToken)
Dynamic port forwarding (
ssh -D): runs a SOCKS proxy onlocalEndPoint(SOCKS 4, 4a and 5, CONNECT, no authentication). Each application connection names its destination, and the server makes the connection, so host names are resolved on the server's side. Use a loopback address: the proxy has no authentication, so anyone who can reach it can use the server's network. To listen beyond loopback, require a password with ForwardDynamicPortAsync(IPEndPoint, NetworkCredential?, CancellationToken).
- ForwardLocalPortAsync(IPEndPoint, string, int, CancellationToken)
Local port forwarding (
ssh -L): listens onlocalEndPointand forwards every connection made to it through the server toremoteHost:remotePort. Use a loopback address unless other machines should be able to use the tunnel, and port 0 to let the system pick a free port (see LocalEndPoint). Forwarding stops when the forwarder or the client is disposed, or the connection ends.
- ForwardLocalPortAsync(IPEndPoint, string, CancellationToken)
Local forwarding to a Unix socket on the server (
ssh -L port:/remote/socket): listens onlocalEndPointand forwards every connection made to it to the Unix socketremoteSocketPathon the server (direct-streamlocal@openssh.com), for example a database or Docker socket there. The forwarder's RemoteSocketPath is the path; its RemoteHost is empty and RemotePort 0. sshd'sAllowStreamLocalForwardingdecides whether the server connects.
- ForwardLocalUnixSocketAsync(string, string, UnixFileMode, CancellationToken)
Local forwarding from a Unix socket to a Unix socket on the server, as ForwardLocalUnixSocketAsync(string, string, CancellationToken), with the socket file's permissions given (see ForwardLocalUnixSocketAsync(string, string, int, UnixFileMode, CancellationToken)).
- ForwardLocalUnixSocketAsync(string, string, int, UnixFileMode, CancellationToken)
Local forwarding from a Unix socket to
remoteHost:remotePort, as ForwardLocalUnixSocketAsync(string, string, int, CancellationToken), with the socket file's permissions given, as ssh_config'sStreamLocalBindMasksets them: for exampleUnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.GroupWrite(0660) lets the owner's group connect too. Connecting to a Unix socket takes write permission. The mode is set before the socket accepts connections. On Windows the socket file is always restricted to the current user, whatever the mode.
- ForwardLocalUnixSocketAsync(string, string, int, CancellationToken)
Local forwarding from a Unix socket (
ssh -L /local/socket:host:port): creates the Unix socketlocalSocketPathhere and forwards every connection made to it through the server toremoteHost:remotePort. The socket file is created owner-only (mode 0600, as ssh's defaultStreamLocalBindMaskgives; on Windows an ACL with only the current user), and removed when the forwarder stops. Unix sockets work on Linux, macOS and Windows 10 and later.
- ForwardLocalUnixSocketAsync(string, string, CancellationToken)
Local forwarding from a Unix socket to a Unix socket on the server (
ssh -L /local/socket:/remote/socket): creates the Unix socketlocalSocketPathhere (owner-only, removed when the forwarder stops) and forwards every connection made to it toremoteSocketPathon the server, for example to use the server's Docker socket with a local client.
- ForwardRemoteDynamicPortAsync(string, int, Func<string, int, bool>?, CancellationToken)
Remote dynamic port forwarding (
ssh -R [bind_address:]portwith no destination, OpenSSH 7.6 and later): asks the server to listen onbindAddress:remotePort, and answers each connection made to it as a SOCKS proxy (4, 4a and 5, CONNECT, no authentication), connecting to the destination it names from this machine. It gives the server's side outbound access through this machine's network, for example to reach an internal package mirror from a build host.
- ForwardRemotePortAsync(string, int, Func<SshForwardedConnection, CancellationToken, Task>, int, CancellationToken)
Remote port forwarding to a handler in this process (what Go's
ssh.Client.Listengives): asks the server to listen onbindAddress:remotePortand passes every connection made to it tohandler, as a SshForwardedConnection with a duplex Stream. Nothing listens on this machine: it serves a port on the server from the application, for example a webhook receiver behind NAT, or a test server that programs on the server connect to.
- ForwardRemotePortAsync(string, int, string, int, CancellationToken)
Remote port forwarding (
ssh -R): asks the server to listen onbindAddress:remotePortand relays every connection made to it tolocalHost:localPort, as reached from this machine. The bind address islocalhostfor the server's loopback only (what ssh uses by default), an address, or empty for every address; sshd'sGatewayPortsdecides whether it honours anything but loopback. Port 0 lets the server pick one (see RemotePort).
- ForwardRemoteUnixSocketAsync(string, Func<SshForwardedConnection, CancellationToken, Task>, int, CancellationToken)
Remote Unix-socket forwarding to a handler in this process: asks the server to listen on the Unix socket
remoteSocketPath(streamlocal-forward@openssh.com) and passes every connection made to it tohandler, as a SshForwardedConnection with a duplex Stream. sshd'sStreamLocalBindUnlinkdecides whether a stale socket file is replaced.
- ForwardRemoteUnixSocketAsync(string, string, int, CancellationToken)
Remote Unix-socket forwarding (
ssh -R /remote/socket:host:port,streamlocal-forward@openssh.com): asks the server to listen on the Unix socketremoteSocketPathand relays every connection made to it tolocalHost:localPort, as reached from this machine. For example, a database here becomes a socket that programs on the server can open. sshd'sStreamLocalBindUnlinkdecides whether a stale socket file is replaced.
- ForwardRemoteUnixSocketAsync(string, string, CancellationToken)
Remote Unix-socket forwarding to a Unix socket here (
ssh -R /remote/socket:/local/socket): for example, a localgpg-agentor Docker socket that programs on the server can use.
- OpenChannelAsync(string, ReadOnlyMemory<byte>, CancellationToken)
Opens a channel of any type (RFC 4254 section 5.1), for a server's own or vendor channel types that SshSharp has no API for, and returns it.
typeSpecificDatais sent as is after the channel type, so encode it as the type defines (an SSHstringis a big-endianuint32length followed by its bytes). Disposing the channel closes it; ShutdownSendAsync(CancellationToken) ends only the writing side.
- OpenTcpTunnelAsync(string, int, CancellationToken)
Opens a TCP connection from the server to
host:port(adirect-tcpipchannel, whatssh -Land ProxyJump use) and returns it as a stream. The host name is resolved by the server, so it can name machines only the server reaches. Disposing the stream closes the connection.
- OpenUnixSocketTunnelAsync(string, CancellationToken)
Opens a connection from the server to the Unix domain socket at
pathon the server (direct-streamlocal@openssh.com, whatssh -L port:/pathuses), for example a database or Docker socket.
- PingAsync(CancellationToken)
Measures the round trip to the server and proves the connection is alive. OpenSSH 9.5 and later answer a transport ping (
ping@openssh.com); other servers get akeepalive@openssh.comrequest, whose answer arrives just as quickly.
- PreventNewSessionsAsync(CancellationToken)
Opens no more sessions on this connection (commands, shells, SFTP), and tells an OpenSSH server to refuse any as well, as ssh does once it knows it will not open another (OpenSSH's
no-more-sessions@openssh.com): a process that later gets hold of this connection cannot quietly start a session on it, and an OpenSSH server drops the connection if one is tried anyway. Sessions already open, port forwarding and tunnels are unaffected. Like ssh, the request goes only to OpenSSH servers (some others abort on it); with others, only this client refuses.
- RekeyAsync(CancellationToken)
Re-exchanges keys now, as ssh's
~Rescape does, and completes once the new keys are in use in both directions. Keys are also renewed on their own after RekeyAfterBytes or RekeyAfterTime, and when the server asks; if a re-exchange is already running, this waits for it instead of starting another. Channels stay open: data waits while the keys change and then continues. The host key must be the same as at the start, or the connection fails.
- RunCommandAsync(string, SshSessionOptions?, SshCommandInput?, CancellationToken)
Runs
commandon the server with environment variables, a terminal or standard input, and collects its output and exit status. The session is set up as StartCommandAsync(string, SshSessionOptions?, CancellationToken) sets it up.standardInputis written while the output is collected, and end-of-file follows it (at once when there is none), so a command that reads its input to the end (cat,sh -s) finishes. A command that exits without reading all of its input is not an error.
- RunCommandAsync(string, CancellationToken)
Runs
commandon the server and collects its output and exit status.
- ScanHostKeysAsync(Func<CancellationToken, ValueTask<Stream>>, SshHostKeyScanOptions?, CancellationToken)
Fetches the server's host keys without authenticating, over streams that
connectopens: one per key type, so it is called several times. For a host behind a jump host, open each stream with OpenTcpTunnelAsync(string, int, CancellationToken).
- ScanHostKeysAsync(string, int, SshHostKeyScanOptions?, CancellationToken)
Fetches the server's host keys without authenticating, as
ssh-keyscandoes: one key exchange per key type the server offers, each disconnected before user authentication. Each key is one the server proved it holds (it signed the exchange), but nothing says the server is the one you meant to reach: compare the fingerprints out of band before trusting them, or use host certificates.
- SendGlobalRequestAsync(string, ReadOnlyMemory<byte>, CancellationToken)
Sends a global request (RFC 4254 section 4), for a server's own or vendor requests that SshSharp has no API for, and waits for the answer.
requestDatais sent as is after the request name andwant replyflag, so encode it as the request defines. A server answers a request it does not know with a failure, which is returned, not thrown.
- StartCommandAsync(string, SshSessionOptions?, CancellationToken)
Starts
commandwith its input and output as streams, for long-running or interactive commands. For a command whose output fits in memory, RunCommandAsync(string, SshSessionOptions?, SshCommandInput?, CancellationToken) is simpler.
- StartShellAsync(SshSessionOptions?, CancellationToken)
Starts the user's login shell, usually with a terminal (Terminal) for interactive use.
- StartSubsystemAsync(string, SshSessionOptions?, CancellationToken)
Starts a subsystem, as
ssh -sdoes: a protocol the server runs by name (sftp,netconf, or one the server configures with sshd'sSubsystem), with no shell in between. The session's StandardInput and StandardOutput carry the subsystem's protocol, byte for byte.