【问题标题】:How to run commands on SSH server in C#?如何在 C# 中在 SSH 服务器上运行命令?
【发布时间】:2015-06-17 05:52:42
【问题描述】:

我需要使用 C# 代码执行此操作:

  1. 在后台打开putty.exe(这就像一个cmd窗口)
  2. 使用 IP 地址登录远程主机
  3. 输入用户名和密码
  4. 一个接一个地执行多个命令。
  5. 运行另一个命令,得到响应,告诉我在此之前运行的命令已成功执行

所以我尝试这样做:

ProcessStartInfo proc = new ProcessStartInfo() 
{
     FileName = @"C:\putty.exe",
     UseShellExecute = true, //I think I need to use shell execute ?
     RedirectStandardInput = false,
     RedirectStandardOutput = false,
     Arguments = string.Format("-ssh {0}@{1} 22 -pw {2}", userName, hostIP, password)
     ... //How do I send commands to be executed here ?
};
Process.Start(proc);

【问题讨论】:

    标签: c# .net ssh ssh.net


    【解决方案1】:

    你可以试试https://sshnet.codeplex.com/。 有了这个,你根本不需要腻子或窗户。 你也可以得到回应。 它看起来像。像这样。

    SshClient sshclient = new SshClient("172.0.0.1", userName, password);    
    sshclient.Connect();
    SshCommand sc= sshclient .CreateCommand("Your Commands here");
    sc.Execute();
    string answer = sc.Result;
    

    编辑:另一种方法是使用 shellstream。

    像这样创建一个 ShellStream:

    ShellStream stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);
    

    然后你可以使用这样的命令:

      public StringBuilder sendCommand(string customCMD)
        {
            StringBuilder answer;
    
            var reader = new StreamReader(stream);
            var writer = new StreamWriter(stream);
            writer.AutoFlush = true; 
            WriteStream(customCMD, writer, stream);
            answer = ReadStream(reader);
            return answer;
        }
    
    private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
        {
            writer.WriteLine(cmd);
            while (stream.Length == 0)
            {
                Thread.Sleep(500);
            }
        }
    
    private StringBuilder ReadStream(StreamReader reader)
        {
            StringBuilder result = new StringBuilder();
    
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                result.AppendLine(line);
            }
            return result;
        }
    

    【讨论】:

    • 您可以通过 NuGet 包轻松获取它。见here。之后,您只需将其添加为参考。
    【解决方案2】:

    虽然@LzyPanda 的回答有效,但使用 SSH“shell”通道 (SshClient.CreateShellStream),只让交互式终端执行自动化命令并不是一个好主意。你会从中得到很多副作用,比如命令提示符、ANSI 序列、某些命令的交互行为等。

    对于自动化,使用 SSH “exec” 通道 (SshClient.CreateCommand):

    using (var command = ssh.CreateCommand("command"))
    {
        Console.Write(command.Execute());
    }
    

    如果需要执行多个命令,重复上面的代码。您可以为一个 SSH 连接创建任意数量的“exec”通道。

    尽管如果命令相互依赖(第一个命令修改了环境,例如后面命令使用的变量),您已经在一个通道中执行它们。为此使用 shell 语法,例如 &&;

    using (var command = ssh.CreateCommand("command1 && command2"))
    {
        Console.Write(command.Execute());
    }
    

    如果您需要连续读取命令输出,请使用:

    using (var command = ssh.CreateCommand("command"))
    {
        var asyncExecute = command.BeginExecute();
        command.OutputStream.CopyTo(Console.OpenStandardOutput());
        command.EndExecute(asyncExecute);
    }
    

    您也可以使用ExtendedOutputStream,其中包含标准错误。见SSH.NET real-time command output monitoring


    不幸的是,SSH.NET 中“exec”通道的实现不允许为命令提供输入。对于该用例,您将需要求助于“shell”通道,直到解决此限制。

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 2023-03-16
      • 2020-10-30
      • 2010-11-03
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      相关资源
      最近更新 更多