Renci ssh.net - Create console screen from form when connected

11,634
    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());
        }
Share:
11,634
Ryan Caputo
Author by

Ryan Caputo

Updated on June 14, 2022

Comments

  • Ryan Caputo
    Ryan Caputo almost 2 years

    I would like to create (I think its a console) screen to input and see output after renci ssh.net connect (or during). I currently have a form1 which gathers the connection info then you push a button to connect through backgroundworker1.

    I was thinking I would need a form2 and backgroundworker2 to keep the screen realtime but I am not sure.

    I can create the form2 but not sure how to get the input and output to connect in realtime, everything works up to this point.

    In general how do you create a input / output screen.

    If I had at least a starting point I think I can go from there.