1

我使用 ssh.net 在 C# 中编写了一个小程序,该程序连接到 SSH 服务器,进行一些更改,并在 SSH 服务器上重新启动 SSHD 服务。

不幸的是,SSH 服务器在一个缓慢的嵌入式系统上运行,并且 SSHD 服务没有足够快地重新启动以无缝地这样做(无需断开客户端)。SSH 服务实际上需要大约一分钟才能重新启动。这可以。

我的代码看起来是这样的:

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");
}

我遇到的问题是 ssh 客户端需要一分钟甚至更长的时间才能确定 SSH 服务器不再响应,并抛出 System.Net.Sockets.SocketException。有什么办法可以缩短这个超时时间?我不希望它重新连接 - 我只是希望它尽快抛出异常。这是某种 ssh.net 特定的超时值,还是 System.Net.Sockets 超时?

4

1 回答 1

2

感谢Hang的建议,下面的代码解决了这个问题:

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");
}

需要注意的是:

  • RunCommand 行现在用于>/dev/null 2>&1摆脱 stdout 和 stderr
  • RunCommand 行现在用于&在后台运行命令
  • try块现在包含一个Console.WriteLine("\tSuccess");, 因为这是最有可能的结果RunCommand()- 它会继续运行而不是抛出任何异常
  • 不再有client.Disconnect()orusing语句,因此没有任何尝试与 ssh 服务器断开连接 - 代码继续运行

这在我的情况下有效的原因是因为我的程序在此之后基本上没有做任何其他事情 - 它只是退出。其他人可能希望等到 SshClient 再次可用,然后正确断开连接以清理和释放资源。

于 2016-03-26T13:56:40.063 回答