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

Lir*_*man 10 .net c# ssh ssh.net

我需要使用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);
Run Code Online (Sandbox Code Playgroud)

Lzy*_*nda 16

您可以尝试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;
Run Code Online (Sandbox Code Playgroud)

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

创建一个ShellStream,如:

ShellStream stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);
Run Code Online (Sandbox Code Playgroud)

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

  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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 我做了,就像你发送的那样:`string answer = sc.Result;`但它每次都返回空...当我在putty.exe中运行它时,战争没有问题 (2认同)

Mar*_*ryl 5

@LzyPanda的答案有效时,使用SSH“ shell”通道(SshClient.CreateShellStream),仅让交互式终端运行,不是自动化命令执行的好主意。您会从中得到很多副作用,例如命令提示符,ANSI序列,某些命令的交互行为等。

为了实现自动化,请使用SSH“ exec”通道(SshClient.CreateCommand):

using (var command = ssh.CreateCommand("command"))
{
    Console.Write(command.Execute());
}
Run Code Online (Sandbox Code Playgroud)

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

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

using (var command = ssh.CreateCommand("command1 && command2"))
{
    Console.Write(command.Execute());
}
Run Code Online (Sandbox Code Playgroud)

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

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

您还可以使用ExtendedOutputStream,同时包含stdout和stderr。请参阅SSH.NET实时命令输出监视


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