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

标签 c# .net 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);

最佳答案

你可以试试 https://github.com/sshnet/SSH.NET . 有了这个,你根本不需要腻子或 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;
    }

关于c# - 如何在 C# 中的 SSH 服务器上运行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891135/

相关文章:

Windows 到 Ubuntu 的 git 连接

c# - Entity Framework AutoDetectChangesEnabled = false 和 .Find

c# - Entity Framework 5 : Entity is lazy loaded but the navigation properties are null when observing the Local collection

amazon-web-services - AWS OpsWorks SSH 权限被拒绝(公钥)

.NET 项目/命名空间组织问题

.net - 为什么我的提交事件没有被 ASP.NET 中的 jQuery 捕获?

visual-studio - Visual Studio Code 远程开发使 AWS 实例崩溃

c# - System.Linq 和 System.Data.Linq 有什么区别?

c# - 如何验证用户是否属于 C#.NET 中的 Active Directory 用户组

c# - 有效地将 IEnumerable 值折叠在一起