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

编程入门 行业动态 更新时间:2024-10-08 12:44:37
本文介绍了如何在C#中的SSH服务器上运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要使用C#代码执行此操作:

I need to execute this action using a C# code:

  • 在后台打开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
  • 所以我正在尝试这样做:

    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服务器上运行命令?

    本文发布于:2023-11-23 21:37:48,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1622926.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:器上   命令   如何在   SSH

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!