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



    }
}
相关推荐
txzz888821 小时前
CentOS-Stream-10 系统安装之网络设置
linux·运维·服务器·网络·计算机网络·centos
qq_4017004121 小时前
嵌入式Linux网口MAC地址修改
linux·运维·macos
秋刀鱼 ..1 天前
第三届信息化教育与计算机技术国际学术会议(IECA 2026)
运维·人工智能·科技·机器学习·制造
我是谁??1 天前
Linux上检查U盘可读和修复
linux·运维·服务器
杰克逊的日记1 天前
怎么排查pod重启
linux·运维·服务器
追逐梦想永不停1 天前
Permission denied (publickey,gssapi-keyex,gssapi-with-mic) 完整避坑总结
运维
KingRumn1 天前
Linux进程间通信之共享内存与消息队列的竞争问题(同步策略)对比
linux·运维·服务器
空中楼阁,梦幻泡影1 天前
Docker安装MinIO
运维·docker·容器·minio·存储
Graceful_scenery1 天前
ROS2核心概念之服务
运维·服务器
徐子元竟然被占了!!1 天前
应用运维目录
运维