gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:57:29 25 4
gpt4 key购买 nike

我需要使用 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/30883237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com