【问题标题】:Execute multiple dependent SSH commands using SSH.NET in C#在 C# 中使用 SSH.NET 执行多个依赖的 SSH 命令
【发布时间】:2019-10-19 09:59:35
【问题描述】:

我想使用带有 SSH.NET 库的 C# 更改 SSH 内的目录:

SshClient cSSH = new SshClient("192.168.80.21", 22, "appmi", "Appmi");

cSSH.Connect();

Console.WriteLine("current directory:");
Console.WriteLine(cSSH.CreateCommand("pwd").Execute());

Console.WriteLine("change directory");
Console.WriteLine(cSSH.CreateCommand("cdr abc-log").Execute());

Console.WriteLine("show directory");
Console.WriteLine(cSSH.CreateCommand("pwd").Execute());

cSSH.Disconnect();
cSSH.Dispose();

Console.ReadKey();

但它不起作用。我还检查了以下内容:

Console.WriteLine(cSSH.RunCommand("cdr abc-log").Execute());

但仍然无法正常工作。

【问题讨论】:

    标签: c# .net ssh putty ssh.net


    【解决方案1】:

    我相信您希望命令影响后续命令。

    但是SshClient.CreateCommand 使用 SSH "exec" 通道来执行命令。这意味着每个命令都在一个独立的 shell 中执行,并且对其他命令没有影响。


    如果您需要以先前命令影响以后命令的方式执行命令(例如更改工作目录或设置环境变量),则必须在同一通道中执行所有命令。为此,请使用适当的服务器外壳构造。在大多数系统上,您可以使用分号:

    Console.WriteLine(cSSH.CreateCommand("pwd ; cdr abc-log ; pwd").Execute());
    

    在*nix服务器上,你也可以使用&&使以下命令仅在前面的命令成功时才执行:

    Console.WriteLine(cSSH.CreateCommand("pwd && cdr abc-log && pwd").Execute());
    

    一些不太常见的系统(例如 AIX)甚至可能没有办法在一个“命令行”中执行多个命令。在这些情况下,您可能需要使用 shell 通道,否则不建议使用。

    另外,当其他命令实际上是第一个命令的子命令时,您可能需要不同的解决方案。

    Providing subcommands to a command (sudo/su) executed with SSH.NET SshClient.CreateShellStream

    【讨论】:

      【解决方案2】:

      这就是我所做的并且对我有用:

      SshClient sshClient = new SshClient("some IP", 22, "loign", "pwd");
      sshClient.Connect();
      
      ShellStream shellStream = sshClient.CreateShellStream("xterm", 80, 40, 80, 40, 1024);
      
      string cmd = "ls";
      shellStream.WriteLine(cmd + "; echo !");
      while (shellStream.Length == 0)
       Thread.Sleep(500);
      
      StringBuilder result = new StringBuilder();
      string line;
      
      string dbt = @"PuttyTest.txt";
      StreamWriter sw = new StreamWriter(dbt, append: true);           
      
       while ((line = shellStream.ReadLine()) != "!")
       {
        result.AppendLine(line);
        sw.WriteLine(line);
       }            
      
       sw.Close();
       sshClient.Disconnect();
       sshClient.Dispose();
       Console.ReadKey();
      

      【讨论】:

      • 不建议将 shell 通道用于命令自动化。 shell 通道旨在实现交互式 SSH 客户端。
      猜你喜欢
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多