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



    }
}
相关推荐
好多知识都想学12 分钟前
第二章Linux 命令概述
linux·运维·服务器
wo32586614514 分钟前
浪潮英政服务器CS5420H2配置阵列时报错The reguested command has inualid arguments.解决方法
运维·服务器
熊峰峰20 分钟前
Linux第0节:Linux环境的搭建
linux·运维·服务器
一点多余.21 分钟前
nginx的使用
运维·nginx
鸭梨山大。42 分钟前
linux命令-iptables与firewalld 命令详解
linux·运维·网络
半夏知半秋1 小时前
linux下的网络抓包(tcpdump)介绍
linux·运维·服务器·网络·笔记·学习·tcpdump
o0o_-_1 小时前
【瞎折腾/ragflow】构建docker镜像并部署使用ragflow
运维·docker·容器
Watink Cpper2 小时前
[多线程]基于环形队列(RingQueue)的生产者-消费者模型的实现
linux·运维·服务器·消费者·生产者·生产者消费者模型
渗透测试老鸟-九青2 小时前
我与红队:一场网络安全实战的较量与成长
运维·服务器·网络·经验分享·安全·web安全·代码审计
Albert XUU3 小时前
nettrace rtt分析器
linux·运维·网络·网络协议·网络安全·腾讯云·运维开发