ASP.NET Core and dependency injection
SshSharp.Extensions.DependencyInjection registers SSH endpoints with Microsoft.Extensions.DependencyInjection, the way
AddHttpClient registers HTTP clients: named endpoints bound from configuration, a factory for new connections, one shared
connection per endpoint that is opened again when it drops, and a health check.
dotnet add package SshSharp.Extensions.DependencyInjection
When to use
- ASP.NET Core applications, worker services, and anything built on the generic host.
- Several components talk to the same servers, and the server details belong in configuration, not code.
How it fits together
flowchart TB
config["Configuration<br/>Ssh:Deploy section,<br/>secrets, environment"] --> options["SshEndpointOptions<br/>named 'deploy'<br/>(validated)"]
options --> factory["ISshClientFactory<br/>ConnectAsync('deploy')"]
factory -->|"a new connection<br/>per call: caller disposes"| job["A job service"]
factory --> provider["ISshConnectionProvider<br/>GetClientAsync('deploy')"]
provider -->|"one shared connection,<br/>reopened when it drops"| api["Endpoints and services"]
provider --> keyed["ISshEndpoint keyed 'deploy'<br/>[FromKeyedServices('deploy')]"]
provider --> health["Health check<br/>AddSsh('deploy'): PingAsync"]
provider -->|"OpenSftpAsync('deploy'):<br/>SFTP sessions on it"| files["SftpFileProvider,<br/>SftpFileSystem"]
provider -->|"UseSshTunnel('deploy'):<br/>direct-tcpip per connection"| http["HttpClient"]
provider -->|"WatchAsync('deploy'):<br/>connected, disconnected, reconnected"| watcher["A hosted service<br/>restoring forwardings"]
Register endpoints
// Program.cs
builder.Services.AddSshClient("deploy")
.BindConfiguration("Ssh:Deploy") // appsettings.json, environment variables, user secrets, Key Vault ...
.ValidateOnStart(); // a missing Host or UserName fails at startup, not on the first request
builder.Services.AddSshClient("db", o => o.ConfigAlias = "prod-db"); // everything from ~/.ssh/config
builder.Services.AddHealthChecks().AddSsh("deploy", tags: ["ready"]);
{
"Ssh": {
"Deploy": {
"Host": "deploy.example.com",
"UserName": "deploy",
"PrivateKeyFiles": [ "~/.ssh/deploy_ed25519" ],
"KnownHostsFiles": [ "/etc/myapp/known_hosts" ],
"KeepAliveInterval": "00:00:30"
}
}
}
Keep secrets out of appsettings.json: bind Password or PrivateKeyPassphrase from user secrets in development
(dotnet user-secrets set "Ssh:Deploy:Password" ...) and from environment variables or a secret store in production.
Run it in a container or Kubernetes
A pod gets secrets as values, not as files in ~/.ssh, and has no known_hosts of its own. Give the endpoint the key's text
(PrivateKeys) and pin the server's host key (HostKeyFingerprints) instead:
{
"Ssh": {
"Deploy": {
"Host": "deploy.example.com",
"UserName": "deploy",
"HostKeyFingerprints": [ "SHA256:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU" ]
}
}
}
The key and its passphrase are not in the file. Set them where the secrets live:
# Development: user secrets.
dotnet user-secrets set "Ssh:Deploy:PrivateKeys:0:Key" "$(cat ~/.ssh/deploy_ed25519)"
dotnet user-secrets set "Ssh:Deploy:PrivateKeys:0:Passphrase" "$(cat ~/.ssh/deploy_ed25519.passphrase)"
# A container: environment variables (a double underscore is the section separator).
Ssh__Deploy__PrivateKeys__0__Key=...
Ssh__Deploy__PrivateKeys__0__Passphrase=...
Ssh__Deploy__HostKeyFingerprints__0=SHA256:...
In Kubernetes, map a secret's entries to those variables:
env:
- name: Ssh__Deploy__PrivateKeys__0__Key
valueFrom:
secretKeyRef: { name: deploy-ssh, key: key }
- name: Ssh__Deploy__PrivateKeys__0__Passphrase
valueFrom:
secretKeyRef: { name: deploy-ssh, key: passphrase }
The registration does not change. With ValidateOnStart, a malformed fingerprint, a key that cannot be read or a wrong passphrase
stops the start, with an error that names the entry and never shows the key or passphrase:
// Program.cs: the same registration as anywhere else. In the container, the configuration comes from environment variables
// or a secret store, and holds the key's text and the pinned fingerprints instead of file paths.
builder.Services.AddSshClient("deploy")
.BindConfiguration("Ssh:Deploy")
.ValidateOnStart(); // a malformed fingerprint, an unreadable key or a wrong passphrase stops the start, by index only
- Fingerprints replace known_hosts. Setting
KnownHostsFilesorAcceptNewHostKeysas well fails validation. List more than one fingerprint to roll a host key over. - Keys from files come first.
PrivateKeyFiles, thenPrivateKeys, thenPassword. - A proxy is a setting too:
"Proxy": "http://proxy.example.com:3128"(orsocks5://). Bind it from a secret store if it carries a password.
The full rules, Key Vault names and the key-per-file provider are in Dependency injection: containers and Kubernetes.
Use the shared connection
Most code should use ISshConnectionProvider: one connection per endpoint, shared by every caller (SSH runs many channels over one
connection at once), opened on first use and again after it drops.
/// <summary>A service that runs many short commands: the shared connection, opened once and reopened when it drops.</summary>
public sealed class ServerStatus(ISshConnectionProvider connections)
{
public async Task<string> LoadAverageAsync(CancellationToken cancellationToken)
{
var client = await connections.GetClientAsync("deploy", cancellationToken); // owned by the provider
return (await client.RunCommandAsync("cat /proc/loadavg", cancellationToken)).StandardOutputText.Trim();
}
}
app.MapGet("/uptime", async (ISshConnectionProvider connections, CancellationToken cancellationToken) =>
{
var client = await connections.GetClientAsync("deploy", cancellationToken); // shared: do not dispose
var result = await client.RunCommandAsync("uptime", cancellationToken);
return result.ExitStatus == 0 ? Results.Text(result.StandardOutputText) : Results.Problem("uptime failed.");
});
app.MapHealthChecks("/healthz");
Take an endpoint by name
Each endpoint is also a keyed service, ISshEndpoint, so a service names its endpoint once, where it is injected:
/// <summary>A service that works with one endpoint, and names it once, where it is injected.</summary>
public sealed class Backups([FromKeyedServices("deploy")] ISshEndpoint deploy)
{
public async Task<string> ListAsync(CancellationToken cancellationToken)
{
var client = await deploy.GetClientAsync(cancellationToken); // the shared connection: do not dispose
return (await client.RunCommandAsync("ls /var/backups", cancellationToken)).StandardOutputText;
}
public async Task<long> SizeAsync(string path, CancellationToken cancellationToken)
{
await using var sftp = await deploy.OpenSftpAsync(cancellationToken); // an SFTP session on it: ours to dispose
return (await sftp.GetAttributesAsync(path, cancellationToken: cancellationToken)).Size ?? 0;
}
}
GetClientAsync is the shared connection and ConnectAsync a new one, as on the provider and the factory; the keyed service is a
singleton over them.
Use SFTP on the shared connection
OpenSftpAsync(name), an extension method on ISshConnectionProvider, opens a new SFTP session on the endpoint's shared connection,
connecting first if it is down. The session is yours to dispose; the connection stays the provider's.
/// <summary>A service that reads files: an SFTP session of its own for each call, on the shared connection.</summary>
public sealed class ReportReader(ISshConnectionProvider connections)
{
public async Task<long> SizeAsync(string path, CancellationToken cancellationToken)
{
await using var sftp = await connections.OpenSftpAsync("deploy", cancellationToken); // the session is ours to dispose
return (await sftp.GetAttributesAsync(path, cancellationToken: cancellationToken)).Size ?? 0;
}
}
It is also the session factory that lets the file adapters follow the shared connection: they keep one session, and open a new one on the reconnected connection after a drop. Static files from the server:
// Static files served from /srv/www on the server, over the shared connection of the "content" endpoint
// (builder.Services.AddSshClient("content")). The provider opens an SFTP session on the first request, and a new one after the
// connection drops (the shared connection is opened again too). It owns those sessions: dispose it when the application stops.
var connections = app.Services.GetRequiredService<ISshConnectionProvider>();
var provider = new SftpFileProvider(ct => connections.OpenSftpAsync("content", ct), "/srv/www",
new SftpFileProviderOptions { CacheDuration = TimeSpan.FromSeconds(30) });
app.UseStaticFiles(new StaticFileOptions { FileProvider = provider, RequestPath = "/content" });
app.Lifetime.ApplicationStopped.Register(provider.Dispose);
An IFileSystem for services that take one, owned by the container:
// An IFileSystem over the shared connection, for services that take one. It keeps one SFTP session and opens a new one after
// the connection drops. The container owns it and disposes it (and its session) with the application; the connection under
// it stays the provider's.
services.AddSingleton<IFileSystem>(sp =>
{
var connections = sp.GetRequiredService<ISshConnectionProvider>();
return new SftpFileSystem(ct => connections.OpenSftpAsync("deploy", ct));
});
- Lifetime. A provider or file system built this way owns its SFTP session: register it as a singleton (the container disposes
it), or dispose it when the application stops. Register it with a factory delegate, as above, so the container owns it; an instance
passed to
AddSingleton(instance)is not disposed by the container. - One session per adapter. Each adapter keeps its own SFTP session on the shared connection; SSH runs them side by side with the commands and other sessions on that connection.
Call an internal API through the server
UseSshTunnel makes an HttpClient from IHttpClientFactory connect through an endpoint's shared connection, so it reaches a
service only the SSH server can reach, such as an API behind a bastion. No local port is opened.
services.AddSshClient("bastion").BindConfiguration("Ssh:Bastion");
// Every connection this client makes goes through the bastion's shared SSH connection; the bastion resolves the host name.
services.AddHttpClient("inventory", http => http.BaseAddress = new Uri("https://inventory.internal.example.com/"))
.UseSshTunnel("bastion");
/// <summary>Uses the tunnelled client like any other named HttpClient.</summary>
public sealed class Inventory(IHttpClientFactory httpClients)
{
public Task<string> HostsAsync(CancellationToken cancellationToken) =>
httpClients.CreateClient("inventory").GetStringAsync("api/hosts", cancellationToken);
}
The SSH server resolves the host name, and TLS runs end to end. See Dependency injection: HttpClient through an endpoint for what happens across a drop.
Restore a forwarding after a reconnect
Forwardings, sessions and running commands end with their connection. WatchAsync reports the shared connection's changes, so a
hosted service can set them up again on each new connection:
/// <summary>
/// Keeps a remote forwarding (port 8080 on the server to this application's port 5000) on the shared connection, and sets it up
/// again on each new connection.
/// </summary>
public sealed partial class ReverseTunnel([FromKeyedServices("deploy")] ISshEndpoint deploy, ILogger<ReverseTunnel> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await ConnectAsync(stoppingToken);
// The first event is the current state; then each change, as it happens.
await foreach (var change in deploy.WatchAsync(stoppingToken))
{
if (change.Kind == SshConnectionEventKind.Disconnected)
{
Dropped(logger, change.EndpointName, change.Error);
await ConnectAsync(stoppingToken); // a Reconnected event follows
continue;
}
try
{
// Connected or Reconnected: forwardings die with their connection, so set this one up on the new connection.
await change.Client.ForwardRemotePortAsync("localhost", 8080, "localhost", 5000, stoppingToken);
}
catch (Exception ex) when (ex is SshException or ObjectDisposedException && !change.Client.IsConnected)
{
// Dropped again already (and perhaps disposed, replaced by a newer connection): the next event says what followed.
}
}
}
/// <summary>Opens the shared connection, trying again until it is up (the provider waits between failed attempts too).</summary>
private async Task ConnectAsync(CancellationToken cancellationToken)
{
while (true)
{
try
{
await deploy.GetClientAsync(cancellationToken);
return;
}
catch (Exception ex) when (ex is SshException or TimeoutException)
{
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
}
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "SSH endpoint {Endpoint} disconnected; reconnecting")]
private static partial void Dropped(ILogger logger, string endpoint, Exception? error);
}
builder.Services.AddHostedService<ReverseTunnel>();
- Connect, then watch. The first event is the current state (
Connected, orDisconnectedwhen it dropped in between), so nothing is missed. - Watching does not reconnect. After
Disconnected, callGetClientAsync(here in a loop);Reconnectedfollows when it succeeds. - Events name the endpoint only. No host or user name is in them;
Errormay hold the server's disconnect text, so log it rather than returning it to a caller. - An event's client may already be gone. By the time a
ConnectedorReconnectedevent is handled, that connection may have dropped and been disposed by a laterGetClientAsync. The example catchesObjectDisposedExceptionas well asSshExceptionwhenIsConnectedis false, rather than letting it stop the host; the next event says what followed.
Reach the server through a bastion
JumpHosts lists bastions in configuration, each with its own user, keys and host key pins:
{
"Ssh": {
"Deploy": {
"Host": "app1.internal.example.com",
"UserName": "deploy",
"PrivateKeyFiles": [ "~/.ssh/deploy_ed25519" ],
"KnownHostsFiles": [ "/etc/myapp/known_hosts" ],
"JumpHosts": [ { "Host": "bastion.example.com", "UserName": "jump", "PrivateKeyFiles": [ "~/.ssh/jump_ed25519" ] } ]
}
}
}
The endpoint's password and keys never reach the bastion, and a hop without host key settings of its own is checked against the
endpoint's KnownHostsFiles. See Dependency injection: jump hosts.
Use the SSH agent
UseAgent offers the agent's keys after the endpoint's own; the keys never enter the process:
services.AddSshClient("deploy", o =>
{
o.Host = "deploy.example.com";
o.UserName = "deploy";
o.KnownHostsFiles.Add("/etc/myapp/known_hosts");
o.UseAgent = true; // the agent's keys, after any key files and keys given as values
});
The agent is an SshAgent registered in the container, if any (SshAgent.FromKeys serves keys held by the application), otherwise
the user's agent. A server process often has no agent; then the endpoint connects with its other credentials. See
Dependency injection: the SSH agent.
Open a connection of your own
ISshClientFactory opens a new connection on each call, which the caller owns. Use it for long jobs that should not share, or
for something that holds a session for the application's lifetime.
/// <summary>A service that wants a connection of its own, for one job, and closes it afterwards.</summary>
public sealed class Deployer(ISshClientFactory ssh)
{
public async Task<int> RestartAsync(string service, CancellationToken cancellationToken)
{
await using var client = await ssh.ConnectAsync("deploy", cancellationToken); // new connection: ours to dispose
var result = await client.RunCommandAsync($"sudo systemctl restart {Commands.Quote(service)}", cancellationToken);
return result.ExitStatus ?? -1;
}
}
Customize the client options
ConfigureClientOptions adjusts the SshClientOptions the endpoint builds, for what the settings do not cover: a host key policy
of your own, keys held elsewhere (SshPrivateKey.FromSigner), a custom proxy. Pinned keys, keys as values, a proxy, jump hosts and
the agent need no code: they are settings. Keep what the endpoint built, jump hosts included:
services.AddSshClient("deploy", o =>
{
o.Host = "deploy.example.com";
o.UserName = "deploy";
o.PrivateKeyFiles.Add("~/.ssh/deploy_ed25519");
// SshClientOptions is immutable: build new options, and keep what the endpoint already set.
o.ConfigureClientOptions = (provider, built) => new SshClientOptions
{
UserName = built.UserName,
Password = built.Password,
PrivateKeys = built.PrivateKeys, // the agent's too, with UseAgent
Proxy = built.Proxy,
JumpHosts = built.JumpHosts,
AddressFamily = built.AddressFamily,
KeepAliveInterval = built.KeepAliveInterval,
ConnectTimeout = built.ConnectTimeout,
Compression = built.Compression,
Logger = built.Logger,
// Changed: host keys checked by a service from the container instead of known_hosts or pinned fingerprints.
HostKeyVerifier = SshHostKeyVerifier.FromDelegate((context, cancellationToken) =>
provider.GetRequiredService<IHostKeyInventory>().IsTrustedAsync(context.Host, context.HostKey.Fingerprint, cancellationToken)),
};
});
Notes and pitfalls
- Do not dispose the shared client.
GetClientAsyncreturns a client the provider owns; the provider disposes it with the container. Dispose clients fromISshClientFactory. - No automatic retries. After a drop, the next
GetClientAsyncreconnects (with a growing delay after failures; a call during the delay fails at once with the last error). A command that was running when the connection dropped fails, and your code decides whether to run it again. The file adapters are the exception: built onOpenSftpAsync, they try a read that met the dropped connection once more on a new session (never a write). - Host keys. Without
ConfigAlias, the endpoint verifies againstKnownHostsFiles(default~/.ssh/known_hosts) withStrictHostKeyChecking yes;AcceptNewHostKeysswitches toaccept-new. In a container, pinHostKeyFingerprintsor mount aknown_hostsfile. ConfigAliasconnects throughssh_configinstead; thenHost,Port,UserName,PrivateKeyFiles,PrivateKeyPassphrase,KnownHostsFiles,AcceptNewHostKeys,KeepAliveIntervalandConfigureClientOptionsare not used, andPrivateKeys,HostKeyFingerprints,ProxyandJumpHostsfail validation.AddressFamilyandCompression, when set, overridessh_config's, andUseAgentset tofalseturns the agent off (trueuses the agent registered in the container, else the user's, in place ofIdentityAgent).- IPv4 or IPv6 only.
AddressFamily(InetorInet6,"AddressFamily": "Inet"in configuration) limits which of the server's addresses are tried, asssh -4and-6do: for a host whose IPv6 address is published but not reachable from the cluster. It is the builtSshClientOptions.AddressFamily. - Timeouts.
ConnectTimeout(30 s) bounds each attempt, authentication included, and fails withTimeoutException. It is also theSshClientOptions.ConnectTimeoutthatConfigureClientOptionsreceives; a shorter one set there applies, and still fails withTimeoutException. WithConfigAlias,ssh_config's ownConnectTimeoutapplies too, and fails withSshException(Reason = Timeout) when it is the shorter. - Health endpoints are often public. The check's description names no server software; the exception is attached for logging, so keep it out of public responses.
- Testing.
ISshClientFactory,ISshConnectionProviderandISshEndpointare interfaces, but they returnSshClient, which only a server can create. Put your own interface in front of the operations you use; see Unit-test code that uses SshSharp.
See also
- Dependency injection (in-depth: every setting)
- A background worker
- The runnable ASP.NET Core and worker service samples