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



    }
}
相关推荐
Jimmy_jimi3 分钟前
利用nginx代理完成url重定位
运维·nginx
liuyicenysabel33 分钟前
多服务上线日记三:
运维·服务器·笔记·学习
一只鹿鹿鹿2 小时前
大数据中心安全系统解决方案(Word文件)
大数据·运维·物联网·安全·政务
AuTumn-L4 小时前
使用 SSH 密钥认证实现安全免密登录
服务器·安全·ssh
领创工作室4 小时前
GitHub Workflows 全面解析:从核心概念到开源实现
运维·github
吕海洋5 小时前
目前可用的docker源2026.08
运维·docker·容器
fb_123456 小时前
Linux运维封神|SELinux详解+CentOS7启动原理+Root密码重置+开机故障排查实战
linux·运维·服务器
~|Bernard|6 小时前
Linux 定时任务(Cron)完整教程
linux·运维·服务器
小周学学学6 小时前
vmware-horizon第一章:horizon服务器安装
运维·服务器·vmware
gsls2008087 小时前
Penpot Docker 部署与 MCP 服务配置文档
运维·docker·容器·原型·penpot