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



    }
}
相关推荐
玩转测试开发19 小时前
xshell设置跳板机登录内网服务器
运维·服务器·数据库
Java 码农19 小时前
linux shell 数组
linux·运维·服务器
大梦谁先觉i19 小时前
Linux 磁盘空间“消失”之谜:文件已删,空间却不释放?
linux·运维·服务器
序属秋秋秋19 小时前
《Linux系统编程之开发工具》【编译器 + 自动化构建器】
linux·运维·服务器·c语言·c++·自动化·编译器
塔能物联运维19 小时前
物联网运维中基于自适应射频环境监测的动态频谱优化技术
运维·物联网
小涂20 小时前
在Linux(deepin-community-25)下安装MongoDB
linux·运维·mongodb
艾莉丝努力练剑20 小时前
【Linux基础开发工具 (一)】详解Linux软件生态与包管理器:从yum / apt原理到镜像源实战
linux·运维·服务器·ubuntu·centos·1024程序员节
月巴月巴白勺合鸟月半20 小时前
生成私钥公钥
运维·服务器
快乐的钢镚子21 小时前
思腾合力云服务器远程连接
运维·服务器·python
小虚竹21 小时前
使用仓颉语言实现 nanoid:一个安全的唯一 ID 生成器
运维·服务器·安全·鸿蒙