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



    }
}
相关推荐
lifewange9 分钟前
Nginx + Kafka 可编程精细控制 完整版(可直接落地运行)
运维·nginx·kafka
hweiyu0038 分钟前
Linux命令:ip6tables
linux·运维·服务器
数字化顾问41 分钟前
(122页PPT)企业数字化IT架构蓝图规划设计方案(附下载方式)
java·运维·架构
ITyunwei09871 小时前
灾难恢复与业务连续性:如何确保天灾人祸下,业务也能“屹立不倒”?
运维·服务器
Promise微笑1 小时前
2026电缆故障定位仪:缆故障定位仪精准选型与高效避坑指南
运维·人工智能·重构
爱喝水的鱼丶1 小时前
SAP-ABAP:新手入门篇——从0到1写出你的第一个ABAP Hello World程序并完成调试运行
运维·服务器·数据库·学习·sap·abap
MY_TEUCK2 小时前
【2026最新Linux虚拟机安装】Linux 虚拟机安装VMware 17 + CentOS 7
linux·运维·centos
再战300年2 小时前
nginx之负载均衡
运维·nginx·负载均衡
Land03292 小时前
指纹浏览器自动化集成方案|多浏览器RPA适配实战记录
运维·人工智能·爬虫·python·selenium·自动化·rpa
hahaha 1hhh3 小时前
用SSH 建立了一个本地端口转发隧道,用于安全地访问远程服务器上的服务,后台运行。autodl
服务器·安全·ssh