I'm using SSH.NET to connect to my Raspberry Pi from a Console Application in C#.
I want to send text from my very own stream, writing to it through a StreamWriter
.
The problem is that it does nothing. It's like the WriteLine("ls")
doesn't produce any effect.
This is the code:
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)
{
}
}
}
}
What's the problem?
Thanks is advance :)
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);