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



    }
}
相关推荐
DY009J14 分钟前
深度探索Kali Linux的精髓与实践应用
linux·运维·服务器
什么鬼昵称1 小时前
Pikachu- Over Permission-垂直越权
运维·服务器
码农小白1 小时前
linux驱动:(22)中断节点和中断函数
linux·运维·服务器
4647的码农历程1 小时前
Linux网络编程 -- 网络基础
linux·运维·网络
醉颜凉2 小时前
银河麒麟桌面操作系统V10 SP1:取消安装应用的安全授权认证
运维·安全·操作系统·国产化·麒麟·kylin os·安全授权认证
C++忠实粉丝2 小时前
Linux环境基础开发工具使用(2)
linux·运维·服务器
康熙38bdc3 小时前
Linux 环境变量
linux·运维·服务器
存储服务专家StorageExpert3 小时前
DELL SC compellent存储的四种访问方式
运维·服务器·存储维护·emc存储
大G哥4 小时前
记一次K8S 环境应用nginx stable-alpine 解析内部域名失败排查思路
运维·nginx·云原生·容器·kubernetes
醉颜凉4 小时前
银河麒麟桌面操作系统修改默认Shell为Bash
运维·服务器·开发语言·bash·kylin·国产化·银河麒麟操作系统