简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM