Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto check if Ssh.NET connection is established successfully?

Tags:

c#

ssh.net

I would like to get to know how Ssh.NET can tell me if the connection is established successfully:

SshClient client = new SshClient("127.0.0.1", 22, "root", "");
client.Connect();

// Connection ok? Then continue, else display error

SshCommand x = client.RunCommand("service apache2 status");
client.Disconnect();
client.Dispose();

And how do I proof the result of "client.RunCommand("service apache2 status");" logically?
E.g. if(x == "apache2 is running")

like image 422
udgru Avatar asked Mar 02 '15 15:03

udgru


2 Answers

You can check the SshClient.IsConnected property:

if (!client.IsConnected)
{
   // Display error
}
like image 200
Yuval Itzchakov Avatar answered Oct 13 '22 01:10

Yuval Itzchakov


You can use client.IsConnected for this

using (var client = new SshClient("127.0.0.1", 22, "root", "")) {
    client.Connect();

    if (client.IsConnected) {
        SshCommand x = client.RunCommand("cd ~");
    } else {
        Console.WriteLine("Not connected");
    }

    client.Disconnect();
}
like image 42
Owain van Brakel Avatar answered Oct 13 '22 02:10

Owain van Brakel