C# SSH Connection

Jake Charman picture Jake Charman · Jan 23, 2016 · Viewed 14.3k times · Source

I'm trying to run SSH commands as part of a C# app. My code is as follows:

using System;
using Renci.SshNet;

namespace SSHconsole
{
    class MainClass
    {

        public static void Main (string[] args)
        {
            //Connection information
            string user = "sshuser";
            string pass = "********";
            string host = "127.0.0.1";

            //Set up the SSH connection
            using (var client = new SshClient (host, user, pass))
            {

                //Start the connection
                client.Connect ();
                var output = client.RunCommand ("echo test");
                client.Disconnect();
                Console.WriteLine (output.ToString());
            }

         }
    }
}

From what I've read about SSH.NET, this should output the result of the command which I believe should be 'test'. However, when I run the program, the output I get is:

Renci.SshNet.SshCommand

Press any key to continue...

I don't understand why I'm getting this output (regardless of the command) and any input would be greatly appreciated.

Thanks,

Jake

Answer

Szabolcs Dézsi picture Szabolcs Dézsi · Jan 23, 2016

Use output.Result instead of output.ToString().

using System;
using Renci.SshNet;

namespace SSHconsole
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            //Connection information
            string user = "sshuser";
            string pass = "********";
            string host = "127.0.0.1";

            //Set up the SSH connection
            using (var client = new SshClient(host, user, pass))
            {
                //Start the connection
                client.Connect();
                var output = client.RunCommand("echo test");
                client.Disconnect();
                Console.WriteLine(output.Result);
            }
        }
    }
}