2016-03-25 21 views
0

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のタイムアウトですか?ハンさんの提案に

+0

私は、Linuxのボックスを使ってリモートサービスを再起動しても、既存のクライアント接続を強制終了せず、TCPKeepAliveやServerAliveIntervalなどを設定して、遅いコマンドで接続がタイムアウトしないようにしていますか?キープアライブを設定しないと約1分で接続が切断されるという印象を受けます。 – Hang

+0

私のSshClientオブジェクトで見つけた唯一の関連するサウンディング値は、client.KeepAliveIntervalとclient.ConnectionInfo.RetryAttemptsです。 KeepAliveIntervalはTCPKeepAliveの別の名前のように聞こえるので、10秒に設定しようとしましたが効果はありませんでした。また、RetryAttemptsを1に設定しても効果はありませんでした。例外をスローするのにまだ1分以上かかります。 TCPKeepAliveとServerAliveIntervalを設定できる別の場所がありますか? – Tal

+0

これは多分:http://fredericiana.com/2009/10/21/keeping-ssh-from-disconnecting-automatically/ – Hang

答えて

0

おかげで、次のコードは、問題を解決した:

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関数ラインは現在、stdoutとstderr
  • を取り除くために >/dev/null 2>&1を使用しています
  • RunCommand行で、&を使用して、バックグラウンドでコマンドを実行します。
  • tryこれはRunCommand()の最も可能性の高い結果であるため、ブロックは今、Console.WriteLine("\tSuccess");が含まれていない - それは、例外
  • を投げるのではなく、行き続けるだろうという事実はclient.Disconnect()またはusing文ではなくなりましたので、何もから切断しようとしませんsshサーバ - コードはちょうど行くつもりです

私の場合はこのプログラムは基本的に何もしません。他の人は、SshClientが再び利用できるようになるまで待つことができ、適切に切断してリソースをクリーンアップして解放することができます。

関連する問題