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



    }
}
相关推荐
wanhengidc2 小时前
物理服务器与云服务器的不同之处
运维·服务器·网络·游戏
kaoa0002 小时前
Linux入门攻坚——58、varnish入门
linux·运维·服务器
安当加密2 小时前
通过ASP认证系统作为 RADIUS 认证服务器:解决异地办公登录安全问题的实践方案*
运维·服务器·安全
gaize12132 小时前
服务器的用途:多元化应用与无限可能
运维·服务器
tuokuac10 小时前
docker中nginx配置报错解决
linux·运维·服务器
Joren的学习记录11 小时前
【Linux运维大神系列】docker详解(四)
linux·运维·docker
Elastic 中国社区官方博客12 小时前
让我们把这个 expense 工具从 n8n 迁移到 Elastic One Workflow
大数据·运维·elasticsearch·搜索引擎·ai·信息可视化·全文检索
( •̀∀•́ )92012 小时前
GitHub Actions SSH 部署密钥
运维·ssh·github
louqle13 小时前
docker基本知识及常用命令汇总
运维·docker·容器
学烹饪的小胡桃13 小时前
【运维学习】实时性能监控工具 WGCLOUD v3.6.2 更新介绍
linux·运维·服务器·学习·工单系统