Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

c# - SSH.NET doesn't process my shell input commands

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 stdout = Console.OpenStandardOutput();
            var shell = ssh.CreateShell(input, stdout, new MemoryStream());
            shell.Start();

            streamWriter.WriteLine("ls");
            
            while (true)
            {               
            }
        }
    }
}

What's the problem?

Thanks is advance :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...