如何在 C# 中的 SSH 服务器上执行 运行 命令?

How to run commands on SSH server in C#?

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

  1. 在后台打开putty.exe(这就像cmd window)
  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);

你可以试试 https://sshnet.codeplex.com/。 有了这个,你根本不需要腻子或 window。 您也可以获得回复。 它会看起来……像这样。

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;
    }

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

对于自动化,使用 SSH“执行”通道 (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,其中包含 stderr。参见


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