0

我在 SSH.NET 中使用 C#。

我想发出 PWD 命令,但找不到任何文档或帮助。我不知道如何使用“SshClient”类。

更新: 我还尝试使用以下代码尝试使用 SshClient 类,但它什么也没做,既没有任何错误,也没有任何异常。

ConnectionInfo ConnNfo = new ConnectionInfo("FTPHost", 22, "FTPUser",
new AuthenticationMethod[]{

   // Pasword based Authentication
   new PasswordAuthenticationMethod("FTPUser","FTPPass")
   }                
   );

using (var ssh = new SshClient(ConnNfo))
{
    ssh.Connect();                
    if (ssh.IsConnected)
    {                    
         string comm = "pwd";
         using (var cmd = ssh.CreateCommand(comm))
         {
            var returned = cmd.Execute();
            var output = cmd.Result;
            var err = cmd.Error;
            var stat = cmd.ExitStatus;
         }
     }
   ssh.Disconnect();
}

什么都没发生。既不是错误也不是异常。在 Visual Studio 控制台上,我得到以下输出。

*SshNet.Logging Verbose:1:向服务器“ChannelRequestMessage”发送消息:“SSH_MSG_CHANNEL_REQUEST:#152199”。

SshNet.Logging 详细:1:来自服务器的 ReceiveMessage:'ChannelFailureMessage':'SSH_MSG_CHANNEL_FAILURE:#0'。*

在 ssh.RunCommand 方法调用中,程序进入某种睡眠状态(或等待大约 1 分钟)。sshCommand.Result 和 sshCommand.Error 变量为空。

4

2 回答 2

1

这是一个简单的示例 - 一种方法。

string host = "myhost";
string user = "root";
string pwd = "#secret#!"; // Don't use hardcoded plain-text passwords if possible - for demonstration only.

using (PasswordAuthenticationMethod auth = new PasswordAuthenticationMethod(user, pwd))
{
    ConnectionInfo connection = new ConnectionInfo(host, user, auth);
    using (var ssh = new SshClient(connection))
    {
        ssh.Connect();
        SshCommand sshCommand = ssh.RunCommand("pwd");
        Console.WriteLine("Command execution result: {0}", sshCommand.Result);
    }
}

注意,如果你指定了一个无效的命令(例如“pwdxxxx”),你不会得到一个异常,而是一个将被存储在SshCommand.Error字符串中的错误。

另请注意,这使用 SSH PasswordAuthentication,它可能未在您的 SSH 配置中启用。

于 2015-12-11T13:54:44.803 回答
0

尝试查看 SSH.NET 的文档:

CodePlex 的 SSH.NET

执行命令的代码示例(推荐)

帮助文件.CHM

于 2015-12-11T13:40:09.203 回答