gpt4 book ai didi

c# - 显示 SSH.NET 的输出

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:46 24 4
gpt4 key购买 nike

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

最佳答案

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

command.Execute()

不返回您的结果。您必须像以前那样执行,然后通过

获取结果
command.Result 

它看起来像这样:

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

希望能帮到你。

关于c# - 显示 SSH.NET 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48445418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com