Sup*_*JMN 2 .net c# ssh stream ssh.net
我正在使用SSH.NET从C#中的控制台应用程序连接到我的Raspberry Pi。
我想从我自己的流中发送文本,并通过StreamWriter
。
问题是它什么也不做。就像WriteLine("ls")
不会产生任何效果。
这是代码:
using System;
using System.IO;
using Renci.SshNet;
namespace SSHTest
{
class Program
{
static void Main(string[] args)
{
var ssh = new SshClient("raspberrypi", 22, "pi", "raspberry");
ssh.Connect();
var input = new MemoryStream();
var streamWriter = new StreamWriter(input) { AutoFlush = true };
var shell =
ssh.CreateShell(input, Console.OpenStandardOutput(), new MemoryStream());
shell.Start();
streamWriter.WriteLine("ls");
while (true)
{
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有什么问题?
谢谢是提前:)
MemoryStream
对于实现输入流而言,它不是一个很好的类。
当你写MemoryStream
,与大多数流实现,它的指针是在写入数据的端部移动。
因此,当SSH.NET通道尝试读取数据时,没有任何内容可供读取。
您可以将指针移回:
streamWriter.WriteLine("ls");
input.Position = 0;
Run Code Online (Sandbox Code Playgroud)
但是正确的方法是使用PipeStream
SSH.NET,它具有单独的读写指针(就像一个* nix管道):
var input = new PipeStream();
Run Code Online (Sandbox Code Playgroud)
另一个选择是使用SshClient.CreateShellStream
(ShellStream
class),它是针对此类任务而设计的。它为您提供了一个Stream
既可以编写又可以阅读的界面。
另请参见是否可以使用SSH.NET从单个登录会话执行多个SSH命令?
虽然SshClient.CreateShell
(SSH“ shell”通道)不是自动执行命令的正确方法。使用“执行”通道。对于简单的情况,请使用SshClient.RunCommand
。如果要连续读取命令输出,请使用SshClient.CreateCommand
来检索命令输出流:
var command = ssh.CreateCommand("ls");
var asyncExecute = command.BeginExecute();
command.OutputStream.CopyTo(Console.OpenStandardOutput());
command.EndExecute(asyncExecute);
Run Code Online (Sandbox Code Playgroud)