Execute long time command in SSH.NET and display the results continuously in TextBox

前端 未结 1 1692
慢半拍i
慢半拍i 2021-02-10 07:20

Is there any way to execute Linux command and display the result in text box in Windows application like PuTTY.

For example I\'m trying to execute the following commands

1条回答
  •  无人及你
    2021-02-10 07:40

    First, do not use "shell" channel to automate a command execution, unless you have a good reason. Use "exec" channel (CreateCommand or RunCommand in SSH.NET).

    To feed the output to a TextBox, just keep reading the stream on a background thread:

    private void button1_Click(object sender, EventArgs e)
    {
        new Task(() => RunCommand()).Start();
    }
    
    private void RunCommand()
    {
        var host = "hostname";
        var username = "username";
        var password = "password";
    
        using (var client = new SshClient(host, username, password))
        {
            client.Connect();
            // If the command2 depend on an environment modified by command1,
            // execute them like this.
            // If not, use separate CreateCommand calls.
            var cmd = client.CreateCommand("command1; command2");
    
            var result = cmd.BeginExecute();
    
            using (var reader =
                       new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
            {
                while (!result.IsCompleted || !reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line != null)
                    {
                        textBox1.Invoke(
                            (MethodInvoker)(() =>
                                textBox1.AppendText(line + Environment.NewLine)));
                    }
                }
            }
    
            cmd.EndExecute(result);
        }
    }
    

    For a slightly different approach, see a similar WPF question:
    SSH.NET real-time command output monitoring.

    Some programs, like Python, may buffer the output, when executed this way. See:
    How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console?

    0 讨论(0)
提交回复
热议问题