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

人盡茶涼 提交于 2019-12-03 08:14:06

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!