Renci ssh.net - 连接时从表单创建控制台屏幕

时间:2015-01-28 15:06:30

标签: c# winforms ssh

我想在renci ssh.net connect(或者)期间创建(我认为它是一个控制台)屏幕来输入和查看输出。 我目前有一个form1收集连接信息,然后你按一个按钮通过backgroundworker1连接。

我在想我需要一个form2和backgroundworker2来保持屏幕实时,但我不确定。

我可以创建form2但不确定如何实时连接输入和输出,一切都可以实现。

一般来说,如何创建输入/输出屏幕。

如果我至少有一个起点,我想我可以从那里开始。

1 个答案:

答案 0 :(得分:2)

    public string inputTo;
    public string outputFrom;
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public static SshClient client { get; set; }
    public ShellStream shellStream { get; set; }

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            Server = textBox1.Text;
            Username = textBox2.Text;
            Password = textBox3.Text;
            client = new SshClient(Server, Username, Password);
            client.Connect();
            string reply = string.Empty;
            shellStream = client.CreateShellStream("dumb", 80, 24, 800, 600, 1024);
            reply = shellStream.Expect(new Regex(@":.*>#"), new TimeSpan(0, 0, 3));
            richTextBox1.Text = "Connected please enter command\r\n#";

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }




    private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
        {
             ShellRunner();
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        client.Disconnect();
        client.Dispose();
    }

    public void ShellRunner()
    {
        try
        {
            var reader = new StreamReader(shellStream);
            int totalLines = richTextBox1.Lines.Length;
            inputTo = richTextBox1.Lines[totalLines - 2];                
            int i  = inputTo.LastIndexOf("#");
            if (i != -1){ shellStream.WriteLine(inputTo.Substring(i + 1)); }
            else { shellStream.WriteLine(inputTo); }
            string result = shellStream.ReadLine(new TimeSpan(0, 0, 3));
            outputFrom = reader.ReadToEnd();
            richTextBox1.AppendText(outputFrom);            
         }

        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }