0

Using Renci SSH.NET, I am trying to send a simple command to an ethernet switch over ssh, and then to read the response back from the switch. I can connect to the switch but it just hangs when I call Execute or RunCommand.

SshClient cSSH = new SshClient(ipValue, "admin", "admin");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("show ip arp");    //this hangs

or

SshClient cSSH = new SshClient(ipValue, "admin", "admin");
cSSH.Connect();
var command = cSSH.CreateCommand("show ip arp");
command.Execute();    //this hangs

So then I tried using StreamReader and StreamWriter like this, and this works but hangs after the last response line and ReadLine() never returns null to end the read loop.

var s = cSSH.CreateShellStream("Commands", 240, 200, 132, 80, 1024);
var reader = new StreamReader(s);
var writer = new StreamWriter(s);
writer.AutoFlush = true;
//Send the command
writer.WriteLine("show ip arp");
writer.Flush();
Thread.Sleep(2000);
string l = "";
string szOut = "";
do
{
    l = reader.ReadLine(); //Hangs on the last line and never returns null
    szOut += l;
} while (l != null);
System.Windows.MessageBox.Show(szOut);

I've tried reader.StreamToEnd() but this also hangs. StreamReader does not support a timeout either.

I feel like I'm not understanding how this is meant to work but I've tried everything I can think of. Surely a synchronous command/response is possible with this library?

0

1 Answer 1

0

Many "devices" do not support SSH "exec" channel (RunCommand in SSH.NET). See


And that your code with use of CreateShellStream hangs is also expected, as a shell is a "stream", that ends only when the connection closes. It does not have an "command end". It's not intended for that you are trying to do. But as your device does not support the "exec" channel, you have to deal with it somehow. You need to implement your own heuristics to detect that you have read complete output [e.g. by detecting a command prompt] and don't call ReadLine again.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks, Martin. Your response made me try a couple of things, one of which worked. writer .WriteLine("show ip arp"); writer .Flush(); writer .WriteLine("exit"); writer .Flush(); This not only gave me a response I could test for to avoid the extra ReadLine() call, but it also gave me a null return code from ReadLine() which I was already testing for. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.