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



    }
}
相关推荐
熊延1 小时前
麒麟V10系统安装部署elasticsearch
linux·运维·服务器·elasticsearch·搜索引擎·全文检索
野指针YZZ2 小时前
一键配置RK3588网络与SSH远程连接
网络·ssh·rk3588
Yeats_Liao4 小时前
评估体系构建:基于自动化指标与人工打分的双重验证
运维·人工智能·深度学习·算法·机器学习·自动化
爱吃生蚝的于勒4 小时前
【Linux】进程信号之捕捉(三)
linux·运维·服务器·c语言·数据结构·c++·学习
文艺理科生Owen5 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
运维·nginx
期待のcode5 小时前
Redis的主从复制与集群
运维·服务器·redis
wangjialelele6 小时前
Linux下的IO操作以及ext系列文件系统
linux·运维·服务器·c语言·c++·个人开发
HypoxiaDream6 小时前
LINUX-Ext系列⽂件系统
linux·运维·服务器
小毛驴8506 小时前
Linux curl 命令用法
linux·运维·chrome
李斯啦果7 小时前
【Linux】Linux目录配置
linux·运维·服务器