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);
            }
        }



    }
}
相关推荐
慧一居士14 分钟前
ubuntu和centos区别对比,使用方式区别对比及示例
运维
johnny_hhh16 分钟前
Confluent 单节点部署配置
运维·阿里云·zookeeper·kafka·centos·数据可视化
星哥说事23 分钟前
零成本上线!用 Hugging Face免费服务器+Docker 快速部署HertzBeat 监控平台
运维·服务器·docker
cly138 分钟前
Jenkins CI/CD 平台详解
运维·ci/cd·jenkins
skywalk816340 分钟前
Ubuntu宽屏显示器只有4:3分辨率问题的解决:用cvt和xrandr命令查看并配置显卡分辨率到1440x900
linux·运维·ubuntu·显示
十月南城1 小时前
微服务化的收益与成本复盘——技术、组织与运维维度的综合账本
运维·微服务·云计算
warton881 小时前
ubuntu24下操作配置mysql8相关目录到指定地址
linux·运维·mysql
peixiuhui1 小时前
EdgeGateway 快速开始手册-串口服务器
运维·人工智能·网关·边缘计算·工业控制·串口服务器·iotgateway
fiveym1 小时前
浪潮服务器BIOS性能优化全方案解析:多场景适配与配置详解
运维·服务器·性能优化
草莓熊Lotso1 小时前
Linux 2.6 内核 O(1) 调度队列深度解析:为什么它能实现常数时间调度?
linux·运维·服务器·数据结构·人工智能·哈希算法·散列表