如何在C#中的SSH服务器上运行命令?
发布时间:2020-12-15 06:17:51 所属栏目:百科 来源:网络整理
导读:我需要使用C#代码执行此操作: 在后台打开putty.exe(这就像一个cmd窗口) 使用其IP地址登录远程主机 输入用户名和密码 一个接一个地执行几个命令. 运行另一个获得响应的命令,告诉我在成功执行之前运行的命令 所以我试着这样做: ProcessStartInfo proc = new
我需要使用C#代码执行此操作:
>在后台打开putty.exe(这就像一个cmd窗口) 所以我试着这样做: 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/.
有了它,你根本不需要腻子或窗户. 你也可以得到答案. 它会看起来……像这样. SshClient sshclient = new SshClient("172.0.0.1",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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |