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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…