carlos E.
carlos E.

Reputation: 115

Displaying Output from SSH.NET

I am fairly new with C# and I am trying to write an SSH console application using the SSH.NET framework. So far I was able to connect to my server successfully, but now I am trying to run commands and have it display the result. Yet, my console comes out blank when I run my application. My end goal was to execute a set of commands and see the results at the end of it.

Program.cs

using Renci.SshNet;
class Program
{
    //Login Parameter
    const String Hostname = "somePort";
    const int PortNumber = 22;
    const String Username = "username";
    const String Password = "root";

    static void Main(string[] args)
    {
        //Bypass Keyboard authentication
        KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
        PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
        kauth.AuthenticationPrompt += new EventHandler<Renci.SshNet.Common.AuthenticationPromptEventArgs>(HandleKeyEvent);

        //Grab info for connections
        ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, PortNumber, Username, pauth, kauth);

        //Connect
        using (SshClient client = new SshClient(connectionInfo))
        {
            try
            {
                //Connect to server
                client.Connect();
                Console.WriteLine("Connection successful");

                var command = client.CreateCommand("ls");
                var result = command.Execute();
                command.Execute();
                Console.WriteLine(result);

                //Disconnect from server
                client.Disconnect();
            }
            //Show exp message
            catch (Exception exp)
            {
                throw exp;
            }
        }       
    }

    //Handle two step auth
    static void HandleKeyEvent(Object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
    {
        foreach (Renci.SshNet.Common.AuthenticationPrompt prompt in e.Prompts)
        {
            if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                prompt.Response = Password;
            }
        }
    }
}

Upvotes: 2

Views: 8159

Answers (1)

internetAlias123
internetAlias123

Reputation: 9

I don't know if you have resolved this issue yet, but the solution is simple in this case. The function:

command.Execute()

doesn't return your result. You have to execute like you did, but then grab the result via

command.Result 

It would look something like this:

 var command = client.CreateCommand("ls");
 command.Execute();
 var result = command.Result;

Hope i could help you.

Upvotes: 1

Related Questions