Table of Contents

Class SshClient

Namespace
Tmds.Ssh
Assembly
Tmds.Ssh.dll

Provides a client for connecting to SSH servers to execute remote commands, forward connections, and perform filesystem operations.

public sealed class SshClient : IDisposable
Inheritance
SshClient
Implements
Inherited Members

Examples

The following example connects to an SSH server and executes a command. It uses default credentials for the current user and authenticates the server against the known_hosts files:

using Tmds.Ssh;

using var sshClient = new SshClient("localhost");
using var process = await sshClient.ExecuteAsync("echo 'hello world!'");
(bool isError, string? line) = await process.ReadLineAsync();
Console.WriteLine(line);

The following example shows how to configure credentials and host authentication explicitly:

using Tmds.Ssh;

string destination = "user@example.com";
string privatekeyFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh/id_rsa");
string trustedServerFingerprint = "BkEYx77wOyUBL8UZfgoYKPLkwLJ7XMrsTwAu5sQC4C8";
string password = "password";

var settings = new SshClientSettings(destination)
{
    Credentials = [ new PrivateKeyCredential(privatekeyFile), new PasswordCredential(password) ],
    UserKnownHostsFilePaths = [ ], // ignore user known_host files.
    HostAuthentication =
    async (KnownHostResult knownHostResult, SshConnectionInfo connectionInfo, CancellationToken cancellationToken) =>
    {
        if (connectionInfo.ServerKey.Key.SHA256FingerPrint == trustedServerFingerprint)
        {
            return true;
        }
        return false;
    }
};

using var sshClient = new SshClient(settings);

The following example shows how to enable logging:

using Microsoft.Extensions.Logging;
using Tmds.Ssh;

using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); // From Microsoft.Extensions.Logging.Console
using var sshClient = new SshClient("localhost", loggerFactory);

Remarks

The SshClient can be created in different ways:

  • Use the constructor that accepts a destination string that uses SSH credentials for the current user for authentication and OpenSSH known_hosts for host key validation.
  • Use the constructor that accepts SshClientSettings to change the default settings.
  • Use the constructor that accepts SshConfigSettings to use configuration from OpenSSH config files.

By default, the connection is established automatically when the first operation is performed (AutoConnect is true). You can also explicitly call ConnectAsync(CancellationToken) to establish the connection before performing operations. When AutoReconnect is enabled, the client will automatically reconnect if the connection is lost unexpectedly.

Once the connection is established, the SshClient methods can be used to execute remote commands, forward connections, and perform filesystem operations.

Constructors

SshClient(string, ILoggerFactory?)

Creates an SshClient for the specified destination.

public SshClient(string destination, ILoggerFactory? loggerFactory = null)

Parameters

destination string

The destination in format [user@]host[:port].

loggerFactory ILoggerFactory

Optional logger factory.

SshClient(string, SshConfigSettings, ILoggerFactory?)

Creates an SshClient for the specified destination with SSH config settings.

public SshClient(string destination, SshConfigSettings sshConfigOptions, ILoggerFactory? loggerFactory = null)

Parameters

destination string

The destination in format [user@]host[:port].

sshConfigOptions SshConfigSettings

SshConfigSettings configuration.

loggerFactory ILoggerFactory

Optional logger factory.

SshClient(SshClientSettings, ILoggerFactory?)

Creates an SshClient with the specified settings.

public SshClient(SshClientSettings settings, ILoggerFactory? loggerFactory = null)

Parameters

settings SshClientSettings

The SshClientSettings.

loggerFactory ILoggerFactory

Optional logger factory.

Properties

Disconnected

Gets a cancellation token that is canceled when the connection is closed.

public CancellationToken Disconnected { get; }

Property Value

CancellationToken

Remarks

A connection must be established before using this property.

This property can not be used when AutoReconnect is true.

Methods

ConnectAsync(CancellationToken)

Connect to the server.

public Task ConnectAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task

Remarks

Calling ConnectAsync(CancellationToken) is optional when AutoConnect is set (default).

Dispose()

Closes the connection and releases resources.

public void Dispose()

ExecuteAsync(string, CancellationToken)

Executes a command.

public Task<RemoteProcess> ExecuteAsync(string command, CancellationToken cancellationToken)

Parameters

command string

The command to execute.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteProcess>

RemoteProcess instance for the command.

ExecuteAsync(string, ExecuteOptions?, CancellationToken)

Executes a command with options.

public Task<RemoteProcess> ExecuteAsync(string command, ExecuteOptions? options = null, CancellationToken cancellationToken = default)

Parameters

command string

The command to execute.

options ExecuteOptions

ExecuteOptions for command execution.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteProcess>

RemoteProcess instance for the command.

ExecuteShellAsync(CancellationToken)

Executes a shell.

public Task<RemoteProcess> ExecuteShellAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteProcess>

RemoteProcess instance for the shell.

ExecuteShellAsync(ExecuteOptions?, CancellationToken)

Executes a shell with options.

public Task<RemoteProcess> ExecuteShellAsync(ExecuteOptions? options = null, CancellationToken cancellationToken = default)

Parameters

options ExecuteOptions

ExecuteOptions for shell execution.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteProcess>

RemoteProcess instance for the shell.

ExecuteSubsystemAsync(string, CancellationToken)

Executes a subsystem.

public Task<RemoteProcess> ExecuteSubsystemAsync(string subsystem, CancellationToken cancellationToken)

Parameters

subsystem string

The subsystem name to execute.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteProcess>

RemoteProcess instance for the subsystem.

ExecuteSubsystemAsync(string, ExecuteOptions?, CancellationToken)

Executes a subsystem with options.

public Task<RemoteProcess> ExecuteSubsystemAsync(string subsystem, ExecuteOptions? options = null, CancellationToken cancellationToken = default)

Parameters

subsystem string

The subsystem name to execute.

options ExecuteOptions

ExecuteOptions for subsystem execution.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteProcess>

RemoteProcess instance for the subsystem.

ListenTcpAsync(string, int, CancellationToken)

Creates a TCP listener.

public Task<RemoteListener> ListenTcpAsync(string address, int port, CancellationToken cancellationToken = default)

Parameters

address string

The address to bind to on the remote server.

port int

The port to bind to on the remote server.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteListener>

A RemoteListener for accepting incoming connections.

ListenUnixAsync(string, CancellationToken)

Creates a Unix domain socket listener.

public Task<RemoteListener> ListenUnixAsync(string path, CancellationToken cancellationToken = default)

Parameters

path string

The Unix socket path on the remote server.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteListener>

A RemoteListener for accepting incoming connections.

OpenSftpClientAsync(CancellationToken)

Opens an SftpClient for file transfer operations.

public Task<SftpClient> OpenSftpClientAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<SftpClient>

SftpClient instance for filesystem operations.

OpenSftpClientAsync(SftpClientOptions?, CancellationToken)

Opens an SftpClient for file transfer operations with options.

public Task<SftpClient> OpenSftpClientAsync(SftpClientOptions? options = null, CancellationToken cancellationToken = default)

Parameters

options SftpClientOptions

SftpClientOptions for the SftpClient.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<SftpClient>

SftpClient instance for filesystem operations.

OpenTcpConnectionAsync(string, int, CancellationToken)

Opens a TCP connection to a remote host.

public Task<SshDataStream> OpenTcpConnectionAsync(string host, int port, CancellationToken cancellationToken = default)

Parameters

host string

The remote host to connect to.

port int

The remote port to connect to.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<SshDataStream>

SshDataStream for the TCP connection.

OpenUnixConnectionAsync(string, CancellationToken)

Opens a Unix domain socket connection.

public Task<SshDataStream> OpenUnixConnectionAsync(string path, CancellationToken cancellationToken = default)

Parameters

path string

The Unix socket path on the remote server.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<SshDataStream>

SshDataStream to the Unix socket.

StartForwardAsync(EndPoint, RemoteEndPoint, CancellationToken)

Starts local port forwarding to a remote endpoint.

public Task<LocalForward> StartForwardAsync(EndPoint bindEP, RemoteEndPoint remoteEP, CancellationToken cancellationToken = default)

Parameters

bindEP EndPoint

The local endpoint to bind to. This can be an IPEndPoint or a UnixDomainSocketEndPoint.

remoteEP RemoteEndPoint

The RemoteEndPoint to forward to. This can be a RemoteHostEndPoint, a RemoteUnixEndPoint or a RemoteIPEndPoint.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<LocalForward>

A LocalForward instance for managing the forward.

StartRemoteForwardAsync(RemoteEndPoint, EndPoint, CancellationToken)

Starts remote port forwarding from a remote endpoint to a local endpoint.

public Task<RemoteForward> StartRemoteForwardAsync(RemoteEndPoint bindEP, EndPoint localEP, CancellationToken cancellationToken = default)

Parameters

bindEP RemoteEndPoint

The RemoteEndPoint to bind to. This can be a RemoteIPListenEndPoint or a RemoteUnixEndPoint.

localEP EndPoint

The local endpoint to forward to. This can be a DnsEndPoint, an IPEndPoint or a UnixDomainSocketEndPoint.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<RemoteForward>

A RemoteForward instance for managing the forward.

StartSocksForward(EndPoint, CancellationToken)

Starts a SOCKS proxy server on the local endpoint that forwards to the remote server.

public Task<SocksForward> StartSocksForward(EndPoint bindEP, CancellationToken cancellationToken = default)

Parameters

bindEP EndPoint

The local endpoint to bind to.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

Task<SocksForward>

A SocksForward instance for managing the proxy.