C# SSH.NET 长命令及时返回

在SSH中执行长时间的命令,SSH.NET及时在文本框中返回连续显示结果。

c# - Execute long time command in SSH.NET and display the results continuously in TextBox - Stack Overflow

博主管理了一个服务器集群,准备上自动巡检工具,测试在C# WINFORM应用程序中获取服务器的耗时命令时,需要及时的返回。

全部代码如下:

using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace MySecureCRT
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();   
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {          
            new Task(() => RunCommand()).Start();
        }

        private void RunCommand()
        {
            string host = "x.x.x.x";
            string username = "x";
            string password = "x";

            using (var client = new SshClient(host, username, password))
            {
                client.Connect();
                var cmd = client.CreateCommand("sh high_check.sh");
                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)
                        {
                            listBox1.Invoke((MethodInvoker)(() => listBox1.Items.Add(line + Environment.NewLine)));
                        }
                    }
                }

                cmd.EndExecute(result);
            }
        }



    }
}

相关推荐

  1. ffmpeg 获取视频时命令及其输出

    2024-02-03 07:00:05       28 阅读
  2. py远程执行命令,获取返回

    2024-02-03 07:00:05       61 阅读
  3. npm 命令及其详细解释

    2024-02-03 07:00:05       34 阅读
  4. ffmpeg 改变帧率,分辨率,时命令

    2024-02-03 07:00:05       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-03 07:00:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-03 07:00:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-03 07:00:05       82 阅读
  4. Python语言-面向对象

    2024-02-03 07:00:05       91 阅读

热门阅读

  1. 架构篇31:如何应对接口级的故障?

    2024-02-03 07:00:05       49 阅读
  2. Kong 速率限制

    2024-02-03 07:00:05       53 阅读
  3. SpringBoot使用Kafka详解含完整代码

    2024-02-03 07:00:05       53 阅读
  4. Kotlin 的 Flow 简单使用

    2024-02-03 07:00:05       41 阅读
  5. python使用fabric库

    2024-02-03 07:00:05       48 阅读
  6. 区块链赋能编程:开启数字世界的新篇章

    2024-02-03 07:00:05       56 阅读
  7. 【Arduino】LGT8F328 UNO R3编译上传

    2024-02-03 07:00:05       51 阅读