ZetCode

C# SSH.NET

last modified November 15, 2026

This article shows how to work with SSH from C# with the SSH.NET library. We run commands on a remote host, verify its host key, upload and download files over SFTP, authenticate with a private key, and handle timeouts.

SSH is a stateful protocol: after a client and a server agree on keys and authenticate, one TCP connection carries channels for commands, file transfers, and port forwarding. SFTP is the file-transfer subsystem that runs inside such a connection, and SCP is the older transfer command. Unlike an HTTP request, an SSH session has a login, a lifetime, and server-side state, so a client has to connect, use the session, and close it.

SSH.NET (namespace Renci.SshNet) is a managed implementation of the client side. The examples use version 2026.0.1, which is MIT-licensed; add it with dotnet add package SSH.NET. The server is an OpenSSH container, because a production server should not be configured for a tutorial. The container is a test fixture: its password is short and its host key is generated on first start.

Running remote commands

Start an OpenSSH server in Docker. The image listens on port 2222, creates the user zetcode with the password secret, and allows password authentication. Mapping the container port to the same host port keeps the client examples simple.

$ docker run -d --name zetcode-ssh -p 2222:2222 \
    -e USER_NAME=zetcode -e USER_PASSWORD=secret \
    -e PASSWORD_ACCESS=true -e SUDO_ACCESS=false \
    lscr.io/linuxserver/openssh-server

The -e options configure the user, the password, and the login methods; SUDO_ACCESS=false keeps the account unprivileged. It takes a few seconds for the server to generate its host keys and start listening. The client project is a console application with the SSH.NET package.

$ dotnet new console -o Client
$ cd Client
$ dotnet add package SSH.NET
Client/Program.cs
using Renci.SshNet;

using var client = new SshClient("localhost", 2222, "zetcode", "secret");
client.Connect();

SshCommand command = client.RunCommand("echo hello from $(whoami); pwd");
Console.WriteLine(command.Result.Trim());
Console.WriteLine($"exit: {command.ExitStatus}");

client.Disconnect();

The client connects, runs a small shell command, and prints the standard output and the exit status. The command uses $(whoami) and pwd so that the result shows which account and directory the session uses.

using var client = new SshClient("localhost", 2222, "zetcode", "secret");
client.Connect();

The four-argument constructor selects password authentication. The port must be passed explicitly because SSH.NET does not read an SSH configuration file. Connect performs the TCP connection, the key exchange, the host key check, and the authentication in one call, and throws if any step fails. The using declaration disposes the session at the end of the program.

SshCommand command = client.RunCommand("echo hello from $(whoami); pwd");
Console.WriteLine(command.Result.Trim());

RunCommand opens a session channel, executes the command through the remote shell, and waits for it to finish. Result holds the standard output, Error holds the standard error, and ExitStatus is the exit code of the remote process. A non-zero exit code does not throw; the caller has to check it. The synchronous methods have asynchronous counterparts such as ConnectAsync and RunCommandAsync.

$ dotnet run
hello from zetcode
/config
exit: 0

Verifying the host key

During the handshake the server proves its identity with a host key. If the client does not check that key, an attacker who can intercept the connection can present a different key and read the password. SSH.NET accepts any host key by default, so a client that does not handle HostKeyReceived is vulnerable to a man-in-the-middle attack.

Client/Program.cs
using Renci.SshNet;
using Renci.SshNet.Common;

using var client = new SshClient("localhost", 2222, "zetcode", "secret");

client.HostKeyReceived += (_, e) =>
{
    Console.WriteLine($"algorithm: {e.HostKeyName}");
    Console.WriteLine($"bits: {e.KeyLength}");
    e.CanTrust = false;
};

try
{
    client.Connect();
}
catch (SshConnectionException ex)
{
    Console.WriteLine($"rejected: {ex.Message}");
}

The handler prints the algorithm and the key size, then rejects the key. Connect throws SshConnectionException with the message Host key could not be verified.

client.HostKeyReceived += (_, e) =>
{
    Console.WriteLine($"algorithm: {e.HostKeyName}");
    Console.WriteLine($"bits: {e.KeyLength}");
    e.CanTrust = false;
};

The event fires before authentication, so a rejected key never receives the password. CanTrust starts as true; setting it to false aborts the connection. A real handler compares e.FingerPrintSHA256 with a value that was pinned when the server was provisioned, and accepts only an exact match. The fingerprint changes when the server is rebuilt, so it belongs in configuration next to the host name, not in a constant buried in code.

e.CanTrust = e.FingerPrintSHA256 == pinnedFingerprint;

The pinning value can come from a configuration file or a secret store, and the comparison should be exact. Accepting a new key automatically, or asking the user to confirm one, turns the protection back into trust-on-first-use. Key rotation is the moment to update the pin deliberately, not an exception to swallow in the handler.

$ dotnet run
algorithm: ssh-ed25519
bits: 256
rejected: Host key could not be verified.

SFTP

SFTP runs over the same authenticated connection and provides file operations with attributes, directories, and random access. SftpClient takes the same connection settings as SshClient.

Client/Program.cs
using System.Text;
using Renci.SshNet;
using Renci.SshNet.Sftp;

await File.WriteAllTextAsync("report.txt", "delivered: 2026-11-15\n");

using var sftp = new SftpClient("localhost", 2222, "zetcode", "secret");
sftp.Connect();

if (!sftp.Exists("/config/archive"))
    sftp.CreateDirectory("/config/archive");

using (FileStream stream = File.OpenRead("report.txt"))
{
    sftp.UploadFile(stream, "/config/archive/report.txt");
}

SftpFileAttributes attributes = sftp.GetAttributes("/config/archive/report.txt");
Console.WriteLine($"size: {attributes.Size}");

var download = new MemoryStream();
sftp.DownloadFile("/config/archive/report.txt", download);
Console.WriteLine(Encoding.UTF8.GetString(download.ToArray()).Trim());

foreach (SftpFile file in sftp.ListDirectory("/config/archive"))
{
    if (file.IsRegularFile)
        Console.WriteLine(file.Name);
}

sftp.RenameFile("/config/archive/report.txt", "/config/archive/report-old.txt");
Console.WriteLine($"renamed: {sftp.Exists("/config/archive/report-old.txt")}");

sftp.DeleteFile("/config/archive/report-old.txt");
sftp.DeleteDirectory("/config/archive");
Console.WriteLine($"removed: {!sftp.Exists("/config/archive")}");

The program creates a directory, uploads a small text file, reads its size and content back, lists the directory, renames the file, and removes both the file and the directory. The output confirms every step.

using var sftp = new SftpClient("localhost", 2222, "zetcode", "secret");
sftp.Connect();

SftpClient opens the sftp subsystem on the server. The connection is independent from an SshClient; a program that needs both can open two sessions or share a ConnectionInfo instance between them. Paths are resolved on the server, and a relative path starts in the user's home directory, which is /config in the container.

using (FileStream stream = File.OpenRead("report.txt"))
{
    sftp.UploadFile(stream, "/config/archive/report.txt");
}

UploadFile copies the stream to the remote path and overwrites an existing file. Wrapping the stream in a using statement closes the local file even if the transfer throws. DownloadFile writes into a stream, and GetAttributes returns the size, timestamps, and permissions without downloading anything.

foreach (SftpFile file in sftp.ListDirectory("/config/archive"))
{
    if (file.IsRegularFile)
        Console.WriteLine(file.Name);
}

ListDirectory returns SftpFile entries, including the . and .. entries; filtering on IsRegularFile skips both and any subdirectories. The other operations follow the same pattern: RenameFile, DeleteFile, CreateDirectory, DeleteDirectory, and Exists, which checks a path without throwing.

$ dotnet run
size: 22
delivered: 2026-11-15
report.txt
renamed: True
removed: True

Key authentication

A private key is safer than a password: it is not guessable, it can be protected with a passphrase, and the server stores only the public half. Generate an Ed25519 key pair on the machine that runs the client, copy the public key into the server's authorized_keys, and fix the ownership so that the login user can read it.

$ ssh-keygen -t ed25519 -f id_ed25519 -N ""
$ docker cp id_ed25519.pub zetcode-ssh:/tmp/key.pub
$ docker exec zetcode-ssh sh -c 'mkdir -p /config/.ssh && \
    cat /tmp/key.pub >> /config/.ssh/authorized_keys && \
    chmod 600 /config/.ssh/authorized_keys && \
    chown -R zetcode:zetcode /config/.ssh'

The empty passphrase keeps the example non-interactive. A real key should have one, supplied by the user or a secret store at run time.

Client/Program.cs
using Renci.SshNet;

var privateKey = new PrivateKeyFile("id_ed25519");
var connectionInfo = new ConnectionInfo("localhost", 2222, "zetcode",
    new PrivateKeyAuthenticationMethod("zetcode", privateKey));

using var client = new SshClient(connectionInfo);
client.Connect();

Console.WriteLine(client.RunCommand("whoami").Result.Trim());
Console.WriteLine(client.RunCommand("echo key authentication works").Result.Trim());

client.Disconnect();

The client reads the private key, builds a PrivateKeyAuthenticationMethod, and passes it to ConnectionInfo. The server accepts the key from authorized_keys and the command reports the login name.

var privateKey = new PrivateKeyFile("id_ed25519");
var connectionInfo = new ConnectionInfo("localhost", 2222, "zetcode",
    new PrivateKeyAuthenticationMethod("zetcode", privateKey));

PrivateKeyFile understands the OpenSSH key formats and the older PEM format. The passphrase overload, new PrivateKeyFile("id_ed25519", passphrase), decrypts a protected key without prompting. ConnectionInfo can hold several authentication methods and tries them in order, which is useful during a migration from passwords to keys.

The private key must stay on the client and must not be committed to source control. The public key is the only part that belongs on the server. After all clients use keys, disable password authentication on the server; the Docker image does that with PASSWORD_ACCESS=false.

$ dotnet run
zetcode
key authentication works

Timeouts and errors

A network client needs limits. The connection timeout covers the TCP connection and the handshake, the keep-alive interval keeps an idle session from being closed by a firewall, and a command timeout stops a remote process that never returns.

Client/Program.cs
using Renci.SshNet;
using Renci.SshNet.Common;

var wrong = new PasswordConnectionInfo("localhost", 2222, "zetcode", "wrong-password")
{
    Timeout = TimeSpan.FromSeconds(5)
};

using (var client = new SshClient(wrong))
{
    try
    {
        client.Connect();
    }
    catch (SshAuthenticationException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

using var valid = new SshClient("localhost", 2222, "zetcode", "secret");
valid.Connect();
valid.KeepAliveInterval = TimeSpan.FromSeconds(30);
Console.WriteLine($"connected: {valid.IsConnected}");

SshCommand command = valid.CreateCommand("sleep 2");
command.CommandTimeout = TimeSpan.FromSeconds(1);

try
{
    command.Execute();
}
catch (SshOperationTimeoutException)
{
    Console.WriteLine("command timed out");
}

valid.Disconnect();
Console.WriteLine($"connected: {valid.IsConnected}");

The first connection uses a wrong password and catches SshAuthenticationException with the server's message. The second connection succeeds, reports IsConnected, runs a command that sleeps longer than its timeout, and catches SshOperationTimeoutException.

var wrong = new PasswordConnectionInfo("localhost", 2222, "zetcode", "wrong-password")
{
    Timeout = TimeSpan.FromSeconds(5)
};

PasswordConnectionInfo exposes the same settings as ConnectionInfo, including Timeout. Without an explicit value the library uses its own default, which may be too long for an interactive program. The exception type distinguishes a rejected login from a network failure: authentication failures are SshAuthenticationException, while a refused or dropped connection surfaces as SshConnectionException or a socket exception.

SshCommand command = valid.CreateCommand("sleep 2");
command.CommandTimeout = TimeSpan.FromSeconds(1);

RunCommand is a shortcut that creates a command, executes it, and returns it. CreateCommand allows the timeout to be set before Execute. When the timeout expires, the client stops waiting and throws; whether the remote process is also killed depends on the server and the command, so a long-running job needs its own cleanup or a supervision mechanism.

$ dotnet run
Permission denied (password).
connected: True
command timed out
connected: False

Security notes

Host key verification is not optional. The default behavior of SSH.NET trusts any key, which makes the password or the session vulnerable to interception. Pin the fingerprint, keep it in configuration, and update it only when the server key changes through a known process.

Prefer public-key authentication, protect private keys with passphrases, and run the client under an account that has only the permissions it needs. A remote command is executed with the privileges of the login user, so a command built from untrusted input is a command injection vulnerability. Pass arguments through the command's quoting rules or, better, avoid a shell and run a fixed program with fixed arguments.

SFTP paths need the same care as local paths. Do not concatenate a client-supplied name onto a base directory without validating it; a value such as ../../etc/passwd escapes the intended directory if the server does not confine the user. Generate server-side names, keep uploads outside executable directories, and check the file type after the transfer. Restrict the account to the SFTP subsystem when it does not need a shell, and use SUDO_ACCESS=false or its equivalent.

SCP still works, but OpenSSH 9 and later implement it over SFTP by default, and the legacy protocol lacks some of the guarantees of SFTP. New code should use SftpClient. Close sessions with Disconnect or Dispose, set timeouts on every connection, and do not log passwords, private keys, or full command lines that contain secrets.

The FluentFTP tutorial covers the FTP alternative, and the HttpClient tutorial covers the HTTP client that most C# services use for remote calls.

Source

SSH.NET on GitHub

SSH.NET on NuGet

RFC 4253: The Secure Shell (SSH) Transport Layer Protocol

OpenSSH manual pages

In this article we have used SSH.NET for remote commands and SFTP in C#. See also the FluentFTP and HttpClient tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.