所以我使用Tamir Sharp ssh库向远程AIX机器发送一些命令并获取一些响应。但是我无法在我给出错误命令的情况下读取响应,并且响应流为空,并且它们没有规定是否没有响应。
所以这是我用来发送命令并匹配预期响应的方法。
public void RunCommand(string cmd, string expected = "", int maxTimeout = 5000)
{
int i = 0;
bool foundExpected = false;
Logger.Log(Status.Info, "Entered Command -> " + cmd);
sshStream.Write(cmd);
Thread.Sleep(500);
do
{
lastCommand = sshStream.ReadResponse();
Logger.Log(Status.Info, lastCommand);
if (lastCommand.Contains(expected))
{
//Logger.Log(Status.Info, "Expected output displayed: " + expected);
foundExpected = true;
Thread.Sleep(500);
break;
}
else
{
i += 500;
Thread.Sleep(500);
}
} while (i < maxTimeout);
if (!foundExpected)
{
Logger.Log(Status.Fail, String.Format("Expected output: {0} not displayed", expected));
throw new Exception(String.Format("Expected output: {0} not displayed", expected));
}
}
这些是Readresponse的库方法实现
public string ReadResponse()
{
int readCount;
StringBuilder resp = new StringBuilder();
byte[] buff = new byte[1024];
Match match;
do
{
readCount = this.Read(buff);
resp.Append(System.Text.Encoding.Default.GetString(buff), 0, readCount);
string s = resp.ToString();
match = m_prompt.Match(s);
} while (!match.Success);
return HandleTerminalChars(resp.ToString());
}
public virtual int Read(byte[] buffer)
{
return Read(buffer, 0, buffer.Length);
}
public override int Read(byte[] buffer, int offset, int count)
{
return m_in.Read(buffer, offset, count);
}
所以我遇到的问题是,当我发布错误的命令时,它会获取响应,但是在while循环的下一次迭代中,它会停留在 lastCommand = sshStream.ReadResponse(),因为流中没有响应如何确保检查通道中是否有任何消息。