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 小时前
JAR逆向工程实战对比:传统工具 vs 自动化解决方案
运维·自动化·jar·jar自动逆向工具·jar逆向源码
早睡冠军候选人3 小时前
Ansible学习----管理复杂的 Play 和 Playbook 内容
运维·学习·云原生·ansible
Robpubking6 小时前
AWS 中 S3 的 server-side encryption 解释与说明
运维·aws
爱喝矿泉水的猛男9 小时前
单周期Risc-V指令拆分与datapath绘制
运维·服务器·risc-v
hakukun9 小时前
docker避免每次sudo方法
运维·docker·容器
杨凯凡9 小时前
Docker Compose:多容器应用编排入门与实战
运维·docker·容器
jason.zeng@15022079 小时前
my.cnf详解
运维·数据库·adb
灵神翁9 小时前
自建node云函数服务器
运维·服务器
TangDuoduo000510 小时前
【IO模型与并发服务器】
运维·服务器·网络·tcp/ip
FOREVER-Q10 小时前
Windows 下 Docker Desktop 快速入门与镜像管理
运维·服务器·windows·docker·容器