使用Plink.exe连接到SSH在C#中测试 [英] Testing using Plink.exe to connect to SSH in C#

查看:531
本文介绍了使用Plink.exe连接到SSH在C#中测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着通过plink.exe连接到UNIX终端。我们的目标是,让我可以阅读文本回字符串。

Im trying to connect to a unix terminal via plink.exe. The goal is so that I can read the text back into a string.

我的两难困境是,我工作的银行使用旧的AS400型系统,我们通常是通过腻子访问。我试图开发一种自动化套件将与系统和运行的工作界面和分析输出等。

My dilema is that the bank I work for uses an old as400 type system that we normally access through putty. I'm trying to develop an automation suite that will interface with the system and run jobs and analyse the outputs etc.

所以,我想我会通过C#砰砰使用。如果我通过运行命令提示符下code我得到的(大致)文本,我需要回去。然而IM患了问题,我的C#code,它只是挂起,我从来没有得到一个效应初探。

So I figured I'd use plink through C#. If I run the code via Command prompt I get (roughly) the text I need back. However im suffering a problem in my C# code in that it just hangs and I never get a reponse.

我想是这样的:

连接到服务器
输入命令
读背屏
//更多命令等。

Connect to server Input command Read back screen //More Commands etc

下面是我的code迄今:

Here is my code so far:

class Program
{
    static void Main(string[] args)
    {

        ProcessStartInfo psi = new ProcessStartInfo(@"C:\Windows\System32\cmd");
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
        psi.UseShellExecute = false;
        psi.CreateNoWindow = false;

        Process process = Process.Start(psi);
        string cmdForTunnel = @"c:\putty\plink -ssh jonkers@bankhq -pw automationhero";
        process.StandardInput.WriteLine(cmdForTunnel);
       // process.WaitForExit();
        Thread.Sleep(30000);
        string output = process.StandardOutput.ReadToEnd();

        Console.WriteLine(output);

        //DoBusinessLogic();
        process.StandardInput.WriteLine("logout");
        Thread.Sleep(10000);

        if (process.HasExited)
        {
            process.Close();
            process.Dispose();
        } 
    }
}

林真的不知道问题的所在,因为正如我所说的香港专业教育学院通过在命令行中使用砰砰测试,但我上面的解决方案只是挂起。在使用计算器其他国家人民解决香港专业教育学院尝试,但没有人似乎为我工作,我不断收到此挂起。和技巧将是非常美联社preciated。

Im not really sure where the issues lie because as I say ive tested in using plink through command line, but with my solution above it just hangs. Ive tried using other peoples solutions on stackoverflow but none of them seem to work for me as I keep getting this hang. And tips would be much appreciated.

修改

现在我已经决定使用Renci夏普SSH文库,并有建立自己的解决这个框架。它的效果要好得多。

I've now decided to use the Renci Sharp SSH library and have build my own framework around this. It works much better.

推荐答案

所以,我只是想测试砰砰自己,那么它的结果是pretty赏心悦目。

So I just wanted to test plink myself and well it's result were pretty pleasing.

我在你不能使用 ReadToEnd的 您发送的退出前命令的评论说,除非要阻止您的电流的主题。

As I said in the comments you can't use ReadToEnd before you send the exit command, unless you want to block your current Thread.

其实你可以只接合之前<$发送一串命令(包括退出注销) C $ C> ReadToEnd的,但我确实认为做阅读asynchrounusly,因为它是更强大的。

Actually you could just send a bunch of commands (including the exit or logout) before engaging the ReadToEnd, but I did suggest to do the Read asynchrounusly as it is more robust.

现在有几个方法可以做到流的异步读取。

Now there are a few ways to do async reading of a stream.

过程类实际上提供了活动被传入数据上调。您可以创建的处理的那些活动
这些事件是:

The Process class actually provides Events that are raised on incoming data. You could create handlers for those Events. These Events are:


  • OutputDataReceived

  • ErrorDataReceived

  • OutputDataReceived
  • ErrorDataReceived

他们的事件处理程序提供包含数据的字符串。

Their event handlers provide strings containing the data.

您可以使用的BeginRead 标准输出/标准输入的的StreamReader 实例。

You could use the BeginRead of the StreamReader instances of stdout/stdin.

但在这里我提供了一个code样品使用简单的多线程,做它在一个更粗暴的方式:

But here I provide a code sample that does it in a more crude way using simple multi-threading:

  public string RequestInfo(string remoteHost, string userName, string password, string[] lstCommands) {
        m_szFeedback = "Feedback from: " + remoteHost + "\r\n";

        ProcessStartInfo psi = new ProcessStartInfo()
        {
            FileName = PLINK_PATH, // A const or a readonly string that points to the plink executable
            Arguments = String.Format("-ssh {0}@{1} -pw {2}", userName, remoteHost, password),
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            RedirectStandardInput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        Process p = Process.Start(psi);

        m_objLock = new Object();
        m_blnDoRead = true;

        AsyncReadFeedback(p.StandardOutput); // start the async read of stdout
        AsyncReadFeedback(p.StandardError); // start the async read of stderr

        StreamWriter strw = p.StandardInput;

        foreach (string cmd in lstCommands)
        {
            strw.WriteLine(cmd); // send commands 
        }
        strw.WriteLine("exit"); // send exit command at the end

        p.WaitForExit(); // block thread until remote operations are done
        return m_szFeedback;
    }

    private String m_szFeedback; // hold feedback data
    private Object m_objLock; // lock object
    private Boolean m_blnDoRead; // boolean value keeping up the read (may be used to interrupt the reading process)

    public void AsyncReadFeedback(StreamReader strr)
    {
        Thread trdr = new Thread(new ParameterizedThreadStart(__ctReadFeedback));
        trdr.Start(strr);
    }
    private void __ctReadFeedback(Object objStreamReader)
    {
        StreamReader strr = (StreamReader)objStreamReader; 
        string line;          
        while (!strr.EndOfStream && m_blnDoRead) 
        {
            line = strr.ReadLine();
            // lock the feedback buffer (since we don't want some messy stdout/err mix string in the end)
            lock (m_objLock) { m_szFeedback += line + "\r\n"; }
        }
    }

所以,如果你想获得一个远程主机呼叫的用户目录的内容:

So if you want to get the contents of the user directory of a remote host call:

String feedback = RequestInfo("remote.ssh.host.de", "user", "password", new string[] { "ls -la" });

显然,你代替你自己的地址,凭证和命令列表。

Obviously you substitute your own address, credentials and command-list.

另外你可能想清除输出字符串。例如。在我的情况我发送到远程主机的命令回显到输出,从而出现在返回的字符串。

Also you might want to clean the output string. e.G. in my case the commands I send to the remotehost are echoed into the output and thus appear in the return string.

这篇关于使用Plink.exe连接到SSH在C#中测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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