I wrote a small program in C# using ssh.net that connects to an SSH server, makes some changes, and restarts the SSHD service on the SSH server.
Unfortunately, the SSH server is being run on a slow embeded system, and the SSHD service is not restarted quickly enough to do so seamlessly (without disconnecting the client). The SSH service actually takes about a minute to restart. This is fine.
My code looks this:
Console.WriteLine("Restarting SSHD service on modem...");
try
{
using (var client = new SshClient(IPAddress, "root", "PASSWORD"))
{
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(10);
client.Connect();
client.RunCommand("service sshd restart");
client.Disconnect();
}
}
catch (System.Net.Sockets.SocketException)
{
//We got disconnected because we just restarted the sshd service
//This is expected
Console.WriteLine("\tSuccess");
}
catch
{
//We got disconnected for some other reason
Console.WriteLine("\tIt appears there was a problem restarting the sshd service");
}
The issue I'm having is that the ssh client takes up to a minute, or sometimes longer, to figure out that the SSH server is no longer responding, and throw a System.Net.Sockets.SocketException. Is there any way to shorten this timeout? I don't want it to reconnect - I just want it to throw the exception sooner. Would this be some sort of ssh.net specific timeout value, or a System.Net.Sockets timeout?
Thanks to Hang's suggestions, the following code has solved the problem:
Console.WriteLine("Restarting SSHD service on modem...");
try
{
var client = new SshClient(IPAddress, "root", "PASSWORD")
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(10);
client.Connect();
client.RunCommand("service sshd restart >/dev/null 2>&1 &");
Console.WriteLine("\tSuccess");
}
catch (System.Net.Sockets.SocketException)
{
//We got disconnected because we just restarted the sshd service
//This is expected
Console.WriteLine("\tSuccess");
}
catch
{
//We got disconnected for some other reason
Console.WriteLine("\tIt appears there was a problem restarting the sshd service");
}
The things to note are:
>/dev/null 2>&1 to get rid of stdout and stderr& to run the command in the backgroundtry block now contains a Console.WriteLine("\tSuccess");, because this is the most likely result of the RunCommand() - the fact that it will keep going instead of throwing any exceptionsclient.Disconnect() or a using statement, so nothing attempts to disconnect from the ssh server - the code just keeps goingThe reason this works in my case is because my program basically does nothing else after this - it just exits. Others may want to wait until the SshClient becomes available again, and disconnect properly to clean up and release the resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With