【问题标题】:Cannot change directory with C# SSH.NET无法使用 C# SSH.NET 更改目录
【发布时间】:2016-04-13 16:00:21
【问题描述】:

当我使用 SSH.NET 库连接到服务器时,默认文件夹是 /mif/stud3/2014/rira1874。当我执行

res = ssh.CreateCommand("cd existingFolder").Execute();
Console.WriteLine(res);

它仍然保留在默认连接文件夹中。这里有什么问题?

完整代码:

public void ConnectWithPassword(string username, string password, string domain, int port)
        {
            bool i = true;
            using (var ssh = new SshClient(CreatePasswordConnectionInfo(username, password, domain)))
            {
                try
                {
                    ssh.Connect();
                    if (ssh.IsConnected)
                    {
                        while(i == true)
                        {
                            string res = Regex.Replace(ssh.CreateCommand("pwd").Execute(), @"\r\n?|\n", "");
                            Console.Write(res + ": ");
                            res = ssh.CreateCommand(Console.ReadLine()).Execute();
                            Console.WriteLine(res);
                        }
                    }
                    else {
                        Console.WriteLine("Not connected");
                    }
                    ssh.Disconnect();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception caught: {0}", e);
                }
            }
        }

【问题讨论】:

  • 我没有看到问题与您的代码中的问题相同 ---> 您的代码有 res = ssh.CreateCommand(Console.ReadLine()).Execute();,而您正在谈论的是 res = ssh.CreateCommand("cd existingFolder").Execute();
  • 我的意思是,当我在控制台中写“cd existingFolder”时,它仍然没有改变目录

标签: c# linux ssh


【解决方案1】:

尝试执行以下操作 string cmdstr = "cd /etc; ls -la"; ssh.Connect(); var cmd = ssh.RunCommand(cmdstr); var result = cmd.Result;

基本上 ssh.net 不允许/支持(我猜)。另一种方法是您可以切换到目录并执行您需要的相应命令。 如果您需要执行某些文件,只需使用上面的示例“cd /etc; ./yourFile”。确保包含分号“;”这样你就可以继续执行了。

【讨论】:

    【解决方案2】:

    您是否检查过目录列表以确保您实际上仍在“/mif/stud3/2014/rira1874”中?看起来你通过 SSH 连接到的地方是一个 *nix 盒子;根据ssh.CreateCommand("pwd").Execute() 行做出这个假设。如果是这种情况,有时控制台上返回/显示的目录列表不会改变。例如,如果我有一个带有以下密码/user/me/home: $ 的控制台,并且我尝试将目录更改为/developer/,我的控制台可能仍会显示我仍在/user/me/home,而实际上我在/user/me/home/developer,但是否则ls 将显示。

    基本上,找到一种方法来确保您实际上并未更改目录,并且命令的返回值不会让您失望。

    【讨论】:

    • 感谢您的回答,虽然在我将目录更改为“Documents”(现有文件夹)并输入ls 后,它不会显示/mif/stud3/2014/rira1874/Documents 内容,但相同我连接到的文件夹。除非我这样做 cd Documents && ls 。但客户端仍然返回到默认文件夹。图片如下:i.imgur.com/a7CBfPC.png
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    相关资源
    最近更新 更多