C# SSH.NET没有';t处理我的shell输入命令
我正在使用SSH.NET从C#中的控制台应用程序连接到Raspberry Pi 我想从自己的流中发送文本,通过C# SSH.NET没有';t处理我的shell输入命令,c#,.net,ssh,stream,ssh.net,C#,.net,Ssh,Stream,Ssh.net,我正在使用SSH.NET从C#中的控制台应用程序连接到Raspberry Pi 我想从自己的流中发送文本,通过流编写器写入 问题是它什么也不做。这就像WriteLine(“ls”)不会产生任何效果 代码如下: using System; using System.IO; using Renci.SshNet; namespace SSHTest { class Program { static void Main(string[] args) {
流编写器写入
问题是它什么也不做。这就像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)
{
}
}
}
}
有什么问题吗
感谢是进步:)MemoryStream
不是实现输入流的好类
当您写入MemoryStream
时,与大多数流实现一样,它的指针在写入数据的末尾移动
因此,当SSH.NET通道尝试读取数据时,它没有任何内容可读取
您可以将指针向后移动:
streamWriter.WriteLine("ls");
input.Position = 0;
但是正确的方法是使用SSH.NET中的PipeStream
,它有单独的读写指针(就像*nix管道):
另一个选项是使用SshClient.CreateShellStream
(ShellStream
类),它是为类似这样的任务而设计的。它为您提供了一个流
接口,您可以编写和读取该接口
另见
尽管SshClient.CreateShell
(SSH“shell”通道)不是自动执行命令的正确方法。使用“exec”频道。对于简单的情况,请使用SshClient.RunCommand
。如果要连续读取命令输出,请使用SshClient.CreateCommand
检索命令输出流:
var command = ssh.CreateCommand("ls");
var asyncExecute = command.BeginExecute();
command.OutputStream.CopyTo(Console.OpenStandardOutput());
command.EndExecute(asyncExecute);
非常感谢!它起作用了,现在它起作用了,我想更进一步。这是另一个问题:顺便说一句,所有代码都是在线的和开源的。它在这里,你应该想看看!
var command = ssh.CreateCommand("ls");
var asyncExecute = command.BeginExecute();
command.OutputStream.CopyTo(Console.OpenStandardOutput());
command.EndExecute(asyncExecute);