ssh-net

How to connect with SSH in C# and SSH.NET

  • 2 min

SSH.NET is a library for .NET written in C# that allows us to connect to remote devices using the SSH protocol in a .NET application.

It is a tool that can be very useful for system administrators and developers looking to automate tasks on remote servers or transfer files over SSH.

SSH.NET allows us to connect to remote devices, obtain server information, execute commands, download or upload files. In short, all the functionalities we can expect or need from an SSH connection.

Given that security is one of SSH’s main objectives, a very important part of the library is providing security functions, such as encryption or authentication with passwords and public/private keys.

Some of the most notable features of SSH.NET are:

  • Secure SSH connection and authentication
  • SCP and SFTP file transfer
  • SSH command execution
  • SSH terminal interaction
  • SSH public and private key handling
  • Password-based and key-based authentication handling

It is compatible with .NET Framework 4.0 or higher, and .NET Standard 1.3 or 2.0. Therefore, it is cross-platform and works on Windows, Linux, and macOS.

How to use SSH.NET

We can easily add the library to a .NET project through the corresponding NuGet package.

Install-Package SSH.NET

Here are some examples of how to use SSH.NET, extracted from the library’s documentation.

using (var client = new SshClient("hostname", "username", "password"))

client.Connect();
Console.WriteLine(client.ConnectionInfo.ServerVersion);

var result = client.RunCommand("ls -l");
Console.WriteLine(result.Result);

using (var ms = new MemoryStream())
{
    client.Download("/home/sshnet/file 123", ms);
}
            
client.Disconnect();
Copied!

This establishes a connection to the server using the specified hostname, username, and password. Then it executes the “ls -l” command on the server and prints the result to the console. After that, it downloads a file and finally closes the connection to the server.