如何在C#中的SSH服务器上运行命令? [英] How to run commands on SSH server in C#?

查看:417
本文介绍了如何在C#中的SSH服务器上运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


  1. 在后台打开putty.exe(这就像cmd窗口一样) )

  2. 使用其IP地址登录到远程主机

  3. 输入用户名和密码

  4. 执行几个命令一个接一个地执行。

  5. 运行另一个命令,该响应得到响应,告诉我在执行之前成功执行的命令

  1. open putty.exe in the background (this is like a cmd window)
  2. login to a remote host using its IP address
  3. enter a user name and password
  4. execute several commands one after the other.
  5. 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);


推荐答案

您可以尝试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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆