SSHサーバーに接続してSSHサーバー上でSSHDサービスを再起動し、SSHサーバーに接続してSSHサーバーに接続する小さなプログラムをC#で作成しました。sshクライアントがsshサーバーから切断されたときに、ssh.netのタイムアウトを減らすにはどうしたらいいですか?
残念ながら、SSHサーバーは低速の組み込みシステム上で実行されており、SSHDサービスは(クライアントを切断せずに)シームレスに再起動するほど速く再起動されません。 SSHサービスは実際に再起動するまで約1分かかります。これは問題ありません。
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のタイムアウトですか?ハンさんの提案に
私は、Linuxのボックスを使ってリモートサービスを再起動しても、既存のクライアント接続を強制終了せず、TCPKeepAliveやServerAliveIntervalなどを設定して、遅いコマンドで接続がタイムアウトしないようにしていますか?キープアライブを設定しないと約1分で接続が切断されるという印象を受けます。 – Hang
私のSshClientオブジェクトで見つけた唯一の関連するサウンディング値は、client.KeepAliveIntervalとclient.ConnectionInfo.RetryAttemptsです。 KeepAliveIntervalはTCPKeepAliveの別の名前のように聞こえるので、10秒に設定しようとしましたが効果はありませんでした。また、RetryAttemptsを1に設定しても効果はありませんでした。例外をスローするのにまだ1分以上かかります。 TCPKeepAliveとServerAliveIntervalを設定できる別の場所がありますか? – Tal
これは多分:http://fredericiana.com/2009/10/21/keeping-ssh-from-disconnecting-automatically/ – Hang