Recently I was trying to build a server management tool. That I need to connect to my server (Ubuntu) programmatically.
I usually access my server via SSH, as a normal human. So I wanna do it with the same approach.
First, create a new .NET Core project with:
dotnet new console
After creating the new project, install the latest SSH.NET library.
Reference: NuGet Gallery | SSH.NET 2020.0.1
And write the following code:
using Renci.SshNet;
using System;
using System.Threading.Tasks;
namespace SSHTest
{
class Program
{
async static Task Main(string[] args)
{
using (var client = new SshClient("ip-or-hostname", "your-username", "your-password"))
{
client.Connect();
var command = client.RunCommand("apt upgrade");
Console.WriteLine(command.ExitStatus);
Console.WriteLine(command.Result);
Console.WriteLine(command.Error);
client.Disconnect();
}
}
}
}
And try to run your app. It gonna automatically connect to your remote server and run the command: apt upgrade
.
The library has much better usage. Check it's doc here: sshnet/SSH.NET: SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism. (github.com)