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

前端之家收集整理的这篇文章主要介绍了如何在C#中的SSH服务器上运行命令?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要使用C#代码执行此操作:

>在后台打开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/.
有了它,你根本不需要腻子或窗户.
你也可以得到答案.
它会看起来……像这样.
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;
    }

猜你在找的C#相关文章