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



    }
}
相关推荐
木卫二号Coding3 小时前
推荐Linux统计文件大小并操作删除工具-ncdu
linux·运维·服务器
志栋智能4 小时前
超自动化运维:实现IT服务消费化的基础
运维·自动化
198******126344 小时前
2026企业AI办公工具选型指南:从评估框架到场景适配
大数据·运维·人工智能
吴声子夜歌4 小时前
Nginx应用与运维——Nginx HTTP模块详解(数据处理功能模块)
运维·nginx·http
2601_967212725 小时前
专利型电源轨道系统技术路线对比与选型框架
大数据·运维·网络·经验分享
数字化顾问6 小时前
(138页PPT)流程体系的建设优化与运营(附下载方式)
大数据·运维·人工智能
2601_967287576 小时前
轮胎侧壁上的 91V 是什么意思,负荷指数与速度级别怎么看
运维·服务器·汽车
小此方7 小时前
Linux网络(十九):TCP流量控制与滑动窗口详解,超时重传和快重传到底有什么区别
linux·运维·服务器·网络·网络协议·tcp/ip
海宇服务7 小时前
零信任架构实战:基于海宇运营商近3个月欠费次数构建自动化履约能力评估管线
运维·人工智能·架构·自动化
码上有光7 小时前
Linux进程通信——共享内存、消息队列和信号量
android·linux·运维·共享内存·通信