Language: EN

ssh-net

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

SSH.NET is a .NET library written in C# that allows us to connect to remote machines 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 machines, obtain server information, execute commands, download or upload files. In short, all the features we can expect or need from an SSH connection.

Being that security is one of the main goals of SSH, a very important part of the library is to provide security functions, such as encryption or authentication with passwords and public/private keys.

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

  • Secure SSH connection and authentication
  • SCP and SFTP file transfer
  • Execution of SSH commands
  • Interaction with the SSH terminal
  • Management of SSH public and private keys
  • Password authentication 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();

Where it 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. Then it downloads a file, and finally, it closes the connection to the server.

The library has a lot of options and functionalities. Although I must say, the documentation is not the best you will find. In case of doubts, look at the Tests (which are not great either 🚀, but better than nothing)

SSH.NET is Open Source under the MIT license, and all the code and documentation is available in the project repository at https://github.com/sshnet/SSH.NET