【发布时间】:2018-07-26 06:13:05
【问题描述】:
我正在尝试为某些路由器/交换机编写一个 SSH 脚本,以使用 SSH.Net 读取信息。我想构建它是异步的,因为它们非常慢且延迟很高。
我可以连接并发送命令,但如果我尝试读出它,我只会得到一些空白行。如果我连续 7 次运行 WriteLine() 方法,我会看到 2 个预期输出。我希望你能帮助我。
这是我的代码:
private static string _srv = "255.255.255.255";
private static string _usr = "looping";
private static string _pwd = "louie";
static void Main(string[] args)
{
GetDslamData();
Console.ReadKey();
}
private static async void GetDslamData()
{
using (SshClient _ssh = new SshClient(_srv, _usr, _pwd))
{
try
{
_ssh.Connect();
if (_ssh.IsConnected)
{
ShellStream stream = _ssh.CreateShellStream("mainstream", 0, 0, 0, 0, 2048);
if (stream.CanWrite)
{
stream.WriteLine("help");
}
if (stream.CanRead)
{
byte[] buffer = new byte[2048];
int i = 0;
if ((i = await stream.ReadAsync(buffer, 0, buffer.Length)) != 1)
{
Console.WriteLine(_ssh.ConnectionInfo.Encoding.GetString(buffer, 0, i));
}
}
}
_ssh.Disconnect();
_ssh.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("Verbindungsfehler! Es konnte keine SSH-Session gestartet werden.");
}
}
}
【问题讨论】:
标签: c# asynchronous ssh async-await