【问题标题】:Process not redirecting complete output; not showing full response from SSH Server进程未重定向完整输出;未显示来自 SSH 服务器的完整响应
【发布时间】:2013-05-17 04:05:27
【问题描述】:

我正在启动一个进程并使用 plink 创建一个反向隧道到我本地网络中的 ssh。

我可以很好地连接到服务器,但它没有在控制台窗口上显示全部内容,我的目标是等待所有内容显示,然后使用 process.standardInput 输入密码继续。

我应该在控制台窗口上收到这个:

Using username "dayan".
Passphrase for key "rsa-key-20130516":

但我只收到第一行:

Using username "dayan".

如果我按下回车键,它确实会为我提供“密码错误”,但我从未看到 “密钥 rsa-key 的密码......”

另外请注意,我确实输入了正确的密码,控制台仍然空白,但是在包含 SSH 服务器的 Linux shell 上,我运行了 who 命令并注意到我已成功连接。

这可能是什么问题?

ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = Path.Combine(BinPath, "plink.exe");

processInfo.Arguments = 
String.Format(@" {0} {1}:127.0.0.1:{2} -i {3} -l {4} {5}", 
remoteOption, LocalPort, TargetPort, KeyPath, username, TargetIp);

processInfo.UseShellExecute = false;
processInfo.CreateNoWindow = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardInput = true;
processInfo.RedirectStandardError = true;

Process process = Process.Start(processInfo);
StreamReader output = process.StandardOutput;

while (!output.EndOfStream) {
    string s = output.ReadLine();
    if (s != "")
        Console.WriteLine(s);
}

process.WaitForExit();
process.Close();

【问题讨论】:

    标签: c# process plink


    【解决方案1】:

    用户名已经在这里提交了:

    processInfo.Arguments = 
    String.Format(@" {0} {1}:127.0.0.1:{2} -i {3} -l {4} {5}", 
    remoteOption, LocalPort, TargetPort, KeyPath, username, TargetIp);
    

    因此,当您启动该进程时,plink 仍会将用户名作为输入处理,并向process.StandardOutput 返回一行。

    现在它等待密码但不结束行,所以string s = output.ReadLine();与程序提交的真实输出不匹配。

    尝试读取输出的每个字节:

      var buffer = new char[1];
      while (output.Read(buffer, 0, 1) > 0)
      {
           Console.Write(new string(buffer));
      };
    

    这也将捕获 CR+LF,因此您不必提及,如果输出必须添加新行。 如果您想手动处理 CR+LF(例如解析特定行),您可以将缓冲区添加到字符串中,并且仅在找到 "\r"":" 或类似的情况下发送它:

      var buffer = new char[1];
      string line = "";
      while (process.StandardError.Read(buffer, 0, 1) > 0)
      {
          line += new string(buffer);
    
          if (line.Contains("\r\n") || (line.Contains("Passphrase for key") && line.Contains(":")))
          {
             Console.WriteLine(line.Replace("\r\n",""));
             line = "";
          }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多