显示SSH.NET的输出

时间:2018-01-25 14:37:29

标签: c# ssh

我是C#的新手,我正在尝试使用SSH.NET框架编写SSH控制台应用程序。到目前为止,我能够成功连接到我的服务器,但现在我正在尝试运行命令并让它显示结果。然而,当我运行我的应用程序时,我的控制台空白。我的最终目标是执行一组命令并在结尾处查看结果。

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

1 个答案:

答案 0 :(得分:1)

我不知道您是否已经解决了这个问题,但在这种情况下解决方案很简单。 功能:

command.Execute()

不会返回您的结果。 你必须像你一样执行,但然后通过

获取结果
command.Result 

它看起来像这样:

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

希望我能帮到你。