Class SshClient
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_hostsfor 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
destinationstringThe destination in format [user@]host[:port].
loggerFactoryILoggerFactoryOptional 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
destinationstringThe destination in format [user@]host[:port].
sshConfigOptionsSshConfigSettingsSshConfigSettings configuration.
loggerFactoryILoggerFactoryOptional logger factory.
SshClient(SshClientSettings, ILoggerFactory?)
Creates an SshClient with the specified settings.
public SshClient(SshClientSettings settings, ILoggerFactory? loggerFactory = null)
Parameters
settingsSshClientSettingsThe SshClientSettings.
loggerFactoryILoggerFactoryOptional logger factory.
Properties
Disconnected
Gets a cancellation token that is canceled when the connection is closed.
public CancellationToken Disconnected { get; }
Property Value
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
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
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
commandstringThe command to execute.
cancellationTokenCancellationTokenToken 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
commandstringThe command to execute.
optionsExecuteOptionsExecuteOptions for command execution.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
- Task<RemoteProcess>
RemoteProcess instance for the command.
ExecuteShellAsync(CancellationToken)
Executes a shell.
public Task<RemoteProcess> ExecuteShellAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationTokenToken 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
optionsExecuteOptionsExecuteOptions for shell execution.
cancellationTokenCancellationTokenToken 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
subsystemstringThe subsystem name to execute.
cancellationTokenCancellationTokenToken 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
subsystemstringThe subsystem name to execute.
optionsExecuteOptionsExecuteOptions for subsystem execution.
cancellationTokenCancellationTokenToken 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
addressstringThe address to bind to on the remote server.
portintThe port to bind to on the remote server.
cancellationTokenCancellationTokenToken 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
pathstringThe Unix socket path on the remote server.
cancellationTokenCancellationTokenToken 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
cancellationTokenCancellationTokenToken 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
optionsSftpClientOptionsSftpClientOptions for the SftpClient.
cancellationTokenCancellationTokenToken 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
hoststringThe remote host to connect to.
portintThe remote port to connect to.
cancellationTokenCancellationTokenToken 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
pathstringThe Unix socket path on the remote server.
cancellationTokenCancellationTokenToken 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
bindEPEndPointThe local endpoint to bind to. This can be an IPEndPoint or a UnixDomainSocketEndPoint.
remoteEPRemoteEndPointThe RemoteEndPoint to forward to. This can be a RemoteHostEndPoint, a RemoteUnixEndPoint or a RemoteIPEndPoint.
cancellationTokenCancellationTokenToken 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
bindEPRemoteEndPointThe RemoteEndPoint to bind to. This can be a RemoteIPListenEndPoint or a RemoteUnixEndPoint.
localEPEndPointThe local endpoint to forward to. This can be a DnsEndPoint, an IPEndPoint or a UnixDomainSocketEndPoint.
cancellationTokenCancellationTokenToken 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
bindEPEndPointThe local endpoint to bind to.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
- Task<SocksForward>
A SocksForward instance for managing the proxy.