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应用程序中获取服务器的耗时命令时,需要及时的返回。

全部代码如下:

cs 复制代码
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);
            }
        }



    }
}
相关推荐
李少兄2 小时前
CentOS系统下前后端项目部署攻略
linux·运维·centos
Two_brushes.4 小时前
【Linux】线程机制深度实践:创建、等待、互斥与同步
linux·运维·服务器·多线程
设计师小聂!6 小时前
Linux系统中部署Redis详解
linux·运维·数据库·redis
努力做小白8 小时前
Linux驱动11 --- buildroot&杂项驱动开发方法
linux·运维·驱动开发·单片机·嵌入式硬件
Sally璐璐8 小时前
Memcache核心技术解析与实战应用
运维·wpf·memcached
哈哈浩丶8 小时前
Linux驱动开发1:设备驱动模块加载与卸载
linux·运维·驱动开发
诗人不说梦^11 小时前
[BUUCTF 2018]Online Tool
linux·运维·服务器
晚风_END12 小时前
Linux|服务器|二进制部署nacos(不是集群,单实例)(2025了,不允许还有人不会部署nacos)
linux·运维·服务器·数据库·编辑器·个人开发
阿沁QWQ13 小时前
应用层协议和JSON的使用
运维·服务器·网络
运维开发王义杰13 小时前
不止于监控:深入剖析OpenTelemetry的可观察性生态体系
运维