SSH.NET doesn't process my shell input commands

谁说我不能喝 提交于 2019-11-29 11:56:54

MemoryStream is not a good class for implementing an input stream.

When you write to MemoryStream, as with most stream implementations, its pointer is moved at the end of the written data.

So when SSH.NET channel tries to read data, it has nothing to read.

You can move the pointer back:

streamWriter.WriteLine("ls");
input.Position = 0;

But the right approach is to use PipeStream from SSH.NET, which has separate read and write pointers (just as a *nix pipe):

var input = new PipeStream();

Another option is to use SshClient.CreateShellStream (ShellStream class), which is designed for task like this. It gives you one Stream interface, that you can both write and read.

See also Is it possible to execute multiple SSH commands from a single login session with SSH.NET?


Though SshClient.CreateShell (SSH "shell" channel) is not the right method for automating command execution. Use "exec" channel. For simple cases, use SshClient.RunCommand. If you want to read a command output continuously, use SshClient.CreateCommand to retrieve the command output stream:

var command = ssh.CreateCommand("ls");
var asyncExecute = command.BeginExecute();
command.OutputStream.CopyTo(Console.OpenStandardOutput());
command.EndExecute(asyncExecute);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!