如何在 C# 中的 SSH 服务器上运行命令? [英] How to run commands on SSH server in C#?
本文介绍了如何在 C# 中的 SSH 服务器上运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用 C# 代码执行此操作:
I need to execute this action using a C# code:
- 在后台打开putty.exe(这就像一个cmd窗口)
- 使用其 IP 地址登录到远程主机
- 输入用户名和密码
- 一个接一个地执行多个命令.
- 运行另一个得到响应的命令,告诉我我之前运行的命令成功执行
所以我想这样做:
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/.有了这个,你根本不需要腻子或窗户.你也可以得到回应.它看起来……像这样.
You could try https://sshnet.codeplex.com/. With this you wouldn't need putty or a window at all. You can get the responses too. It would look sth. like this.
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.
Another approach would be to use a shellstream.
像这样创建一个 ShellStream:
Create a ShellStream once like:
ShellStream stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);
然后你可以使用这样的命令:
Then you can use a command like this:
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# 中的 SSH 服务器上运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文