4

使用Renci.SshNet库。我正在尝试执行一些命令。执行“命令 1”后,我正在执行需要更多时间的“命令 2”。

我只得到输出的第一行。(reader.ReadToEnd()没有以正确的方式工作)。

我也试过while (!reader.EndOfStream){ }没有运气。

我认为这是因为服务器响应的延迟。当没有响应时,流什么也不读并完成。

我找到了解决方案

String tmp;
TimeSpan timeout = new TimeSpan(0, 0, 3);
while ((tmp = s.ReadLine()) != null)
{
    Console.WriteLine(tmp);
}

但这并不专业。我需要某种方式在流结束时结束。

using (var vclient = new SshClient("host", "username", "password"))
{
    vclient.Connect();
    using (ShellStream shell = vclient.CreateShellStream("dumb", 80, 24, 800, 600, 1024))
    {
        Console.WriteLine(SendCommand("comand 1", shell));
        Console.WriteLine(SendCommand("comand 2", shell));
        shell.Close();
    }
    vclient.Disconnect();
}

public static string SendCommand(string cmd, ShellStream sh)
{
    StreamReader reader = null;
    try
    {
        reader = new StreamReader(sh);
        StreamWriter writer = new StreamWriter(sh);
        writer.AutoFlush = true;
        writer.WriteLine(cmd);
        while (sh.Length == 0)
        {
            Thread.Sleep(500);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("exception: " + ex.ToString());
    }
    return reader.ReadToEnd();
}               
4

1 回答 1

7

贝壳是源源不断的。没有发送命令——接收输出序列。ReadToEnd无法知道一个命令的输出在哪里结束。您所能做的就是阅读,直到您自己知道输出结束为止。如果您不能说出来,您可以通过附加某种输出结束标记来帮助自己,例如:

command 1 ; echo this-is-the-end-of-the-output

并阅读,直到你得到"this-is-the-end-of-the-output"线。


通常,“外壳”通道不是自动化的理想解决方案。它旨在用于交互式会话。

您最好使用“exec”通道使用SshClient.CreateCommand. CreateCommand一旦命令完成,通道就会关闭。所以有明确的“流的尽头”,是什么让你的ReadToEnd()工作如你所愿。SSH.NET 甚至可以在SshCommand.Result(内部使用ReadToEnd())中提供整个命令输出。

于 2015-12-11T07:48:31.053 回答