本文介绍了如何在C#中的SSH服务器上运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在后台打开putty.exe(这就像cmd窗口一样) ) 使用其IP地址登录到远程主机 输入用户名和密码 执行几个命令一个接一个地执行。 运行另一个命令,该响应得到响应,告诉我在执行之前成功执行的命令
open putty.exe in the background (this is like a cmd window)
login to a remote host using its IP address
enter a user name and password
execute several commands one after the other.
run another command that gets a response telling me that the commands I ran before that where executed successfully
我需要使用C#代码执行此操作:
I need to execute this action using a C# code:
所以我正在尝试这样做:
So I'm trying to do it like this:
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);推荐答案
您可以尝试sshnet.codeplex/ 。 这样,您根本不需要油灰或窗户。 您也可以获得答复。 看起来……。
You could try sshnet.codeplex/. 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服务器上运行命令?
发布评论