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



    }
}
相关推荐
哲讯智能科技2 小时前
苏州SAP代理商:哲讯科技助力企业数字化转型
大数据·运维·人工智能
十五年专注C++开发2 小时前
Qt .pro配置gcc相关命令(三):-W1、-L、-rpath和-rpath-link
linux·运维·c++·qt·cmake·跨平台编译
qq_628515762 小时前
Centos与RockLinux设置静态ip
linux·运维·centos
程序员老乔2 小时前
【Dify系列】【一】【安装与部署】【ubuntu22.04安装docker部署dify1.4.2】
运维·docker·容器
沧浪之水120101373 小时前
linux常用命令
linux·运维·服务器
梦会实现4 小时前
无外接物理显示器的Ubuntu系统的远程桌面连接(升级版)
linux·运维·ubuntu·计算机外设
Hello.Reader4 小时前
NGINX 四层共享内存区同步模块实战 `ngx_stream_zone_sync_module`
运维·nginx
暗离子跃迁4 小时前
达梦数据库单机部署dmhs同步复制(dm8->kafka)
linux·运维·数据库·分布式·学习·kafka·达梦数据库
北城笑笑4 小时前
Server 11 ,⭐通过脚本在全新 Ubuntu 系统中安装 Nginx 环境,安装到指定目录( 脚本安装Nginx )
linux·运维·前端·nginx·ubuntu
zsyzClb4 小时前
总结用ubuntu一直以来遇到的问题
linux·运维·ubuntu