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



    }
}
相关推荐
谢娘蓝桥4 分钟前
Mac mini 4 docker 安装openclaw
运维·docker·容器
XHW___0015 分钟前
linux 解决挖矿病毒的方法
linux·运维·服务器
bu_shuo9 分钟前
Windows电脑使用VSCode远程控制Windows主机方法记录
windows·vscode·ssh·powershell
李钢蛋12 分钟前
内网跨服务器定时同步指定数据库最新备份
运维·服务器
J超会运15 分钟前
从零部署Nginx:Web全栈实战指南
运维·前端·nginx
乾元19 分钟前
本地大模型:如何在内网部署 Llama/Qwen 等安全增强模型
运维·网络·人工智能·安全·机器学习·llama·安全架构
流水迢迢lst19 分钟前
Linux概述及基础命令
linux·运维·服务器
醇氧21 分钟前
Window 查看是否安装wsl
linux·运维·服务器
cyw899822 分钟前
docker 安装 ollama 并运行
运维·docker·容器
进击切图仔22 分钟前
docker compose 的简单使用
运维·docker·容器