代码之家  ›  专栏  ›  技术社区  ›  4est

使用c运行并执行ssh命令#

  •  0
  • 4est  · 技术社区  · 5 年前

    我想在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());
    

    但仍然不起作用。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Martin Prikryl    5 年前

    我相信你希望这些命令影响后续的命令。

    但是 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());
    
        2
  •  0
  •   4est    5 年前

    这就是我所做的和为我工作的:

    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();
    
    推荐文章