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



    }
}
相关推荐
BizObserver8 分钟前
从 SEO 到 GEO:2026 年品牌信息分发逻辑的颠覆性变革
大数据·运维·网络·人工智能·安全
狂奔蜗牛飙车27 分钟前
大数据赛项(中职组)-VMware+CentOS 7环境安装
linux·运维·centos·大数据应用与服务·大数据入门指南·中职组大数据应用及服务赛项·vmware中装centos7
蚰蜒螟41 分钟前
深度剖析:从 clone3 到 start_routine —— Linux 新线程的“破茧成蝶”之旅
java·linux·运维
空中海1 小时前
Nginx 知识体系 · 下篇:高级与实战
运维·nginx·spring
小五传输1 小时前
内外网文件交换系统产品推荐:安全高效一体化,破解内外网传输难题
大数据·运维·安全
佳xuan1 小时前
linux运维
linux·运维·服务器
如果'\'真能转义说1 小时前
《数据不丢失!本地挂载的 Docker 一键启动PS1脚本》
运维·docker·容器
aramae2 小时前
Linux多线程编程(二):互斥锁、线程安全与死锁剖析
linux·运维·服务器·网络·安全·centos
爱学习的小囧2 小时前
ESXi 存储路径丢失(PDL/APD)完整处置教程:分清类型再操作,一步不踩坑
linux·运维·服务器·网络·esxi·vmware
Lumos_7772 小时前
Linux -- 信号
linux·运维·服务器