plink.exe:服务器意外关闭网络连接

时间:2015-02-03 12:34:00

标签: c# .net ssh putty plink

我们正在开发一个带有C#的winforms客户端,用于使用plink.exe发送SSH命令。我们有以下方法。但我们执行它,标准错误给出“致命错误:服务器意外关闭网络连接”。

在命令行中成功执行相同的命令(plink.exe + arguments)。

有什么想法吗?

感谢。

    public string SendSSHCommand(string host, string userName, string password, string commandFile, string logPath, int maxRetryCount)
    {
        string result = String.Empty;
        string commandText = "plink.exe";

        Process sshProcess = new Process();
        sshProcess.StartInfo = new ProcessStartInfo(commandText);
        sshProcess.StartInfo.Arguments = String.Format("{0} -P 22 -ssh -l {1} -pw {2} <\"{3}\"> \"{4}\"", host, userName, password, commandFile, logPath);

        sshProcess.StartInfo.WorkingDirectory = Parameters.RootDirectory;
        sshProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        sshProcess.StartInfo.CreateNoWindow = true;
        sshProcess.StartInfo.UseShellExecute = false;
        sshProcess.StartInfo.RedirectStandardInput = true;
        sshProcess.StartInfo.RedirectStandardError = true;
        sshProcess.StartInfo.RedirectStandardOutput = true;
        //sshProcess.EnableRaisingEvents = true;

        _logger.Log("SSH Command : " + commandText + " " + sshProcess.StartInfo.Arguments);

        int iteration = 0;

        while (iteration <= maxRetryCount)
        {
            iteration++;
            sshProcess.Start();

            //Thread.Sleep(2000); // wait for two seconds.

            sshProcess.StandardInput.WriteLine("y");
            sshProcess.WaitForExit();

            string output = sshProcess.StandardOutput.ReadToEnd();
            string error = sshProcess.StandardError.ReadToEnd();

            _logger.Log("STANDARD OUTPUT : " + output);
            _logger.Log("STANDARD ERROR : " + error);

            if (File.Exists(logPath))
            {
                using (StreamReader sr = new StreamReader(logPath))
                {
                    result = sr.ReadToEnd();
                }

                File.Delete(logPath);
            }
            else
            {
                result = "NO RESULT FILE";
            }

            if (String.IsNullOrEmpty(result)) // retry needed.
            {
                _logger.Log("SSH command failed. Retrying after 5 seconds...");
                Thread.Sleep(5000);
            }
            else
            {
                break;  // command executed. no retry needed.
            }
        }

        if (iteration >= maxRetryCount)
        {
            _logger.Log("Max retry count is reached.");
            throw new Exception("SSH command failed after " + maxRetryCount.ToString() + " attempts.\nFailed command :\n" + commandText + " " + sshProcess.StartInfo.Arguments);
        }

        return result;
    }

0 个答案:

没有答案