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



    }
}
相关推荐
Tokai_Teio_118 分钟前
第四届黄河流域 misc
运维·服务器
hj2862511 小时前
Linux 网络服务综合笔记(概念 + 命令 + 实操案例)2
linux·运维·网络
what_20181 小时前
Linux 磁盘 (查看、划分、inode)
linux·运维·服务器
ManageEngine卓豪1 小时前
从性能故障到安全风险,现代企业数字化转型下的网络丢包运维管控指南
运维·网络安全·网络故障·网络丢包
Urbano2 小时前
工装 T 恤、Polo 衫全生产工序、痛点解析及多品牌自动化设备应用方案
运维·自动化
AOwhisky2 小时前
Redis 学习笔记(第一期):概述、安装配置与核心理论
运维·数据库·redis·笔记·学习·云计算
AOwhisky3 小时前
Redis 学习笔记(第四期):高可用与集群(哨兵 + Cluster + 容器化)
linux·运维·数据库·redis·笔记·学习·缓存
C语言小火车3 小时前
嵌入式Linux应用开发技术栈完全指南
linux·运维·服务器
IT WorryFree3 小时前
FortiGate 排错常用OID速查表(含Trap OID+轮询OID)
运维·网络
m0_738120723 小时前
渗透测试基础——基于Docker的Rsync服务靶场搭建与原理讲解
运维·服务器·网络·安全·web安全·docker·容器