从C#的ShellStream获取完整的命令输出
本文关键字:命令 输出 获取 ShellStream | 更新日期: 2023-09-27 18:26:22
使用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();
}
外壳是源源不断的。没有发送命令-接收输出序列。ReadToEnd
无法知道一个命令的输出在哪里结束。你所能做的就是阅读,直到你自己知道输出结束。如果你不能说出这一点,你可以通过附加某种输出结束标记来帮助自己,比如:
command 1 ; echo this-is-the-end-of-the-output
读到"this-is-the-end-of-the-output"
行。
一般来说;外壳;通道不是自动化的理想解决方案。这是一个互动会议。
你最好用";exec";信道使用CCD_ 5。对于CreateCommand
,一旦命令完成,通道就会关闭。所以有一个明确的";流的末端";,是什么让ReadToEnd()
如您所期望的那样工作。SSH.NET甚至在SshCommand.Result
(内部使用ReadToEnd()
)中提供了整个命令输出。