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



    }
}
相关推荐
万山y20 小时前
WSL SSH 服务器一站式配置教程
运维·服务器·ssh
半梦半醒*20 小时前
Prometheus监控物理服务器
linux·运维·服务器·centos·prometheus
恒创科技HK20 小时前
高防服务器分为哪几种?香港高防服务器有什么特点?
运维·服务器·安全
黑马金牌编程20 小时前
如何判断一台服务器是否负载过高?
linux·运维·性能调优·性能分析·故障排查
WnHj20 小时前
DORIS 服务器宕机重启后出现的问题
运维·服务器
小锋学长生活大爆炸20 小时前
【知识】Linux将多条指令合并为一条执行
linux·运维·ubuntu
心灵宝贝1 天前
CentOS 7 安装 bzip2-libs-1.0.6-13.el7.x86_64.rpm 的详细步骤
linux·运维·centos
九皇叔叔1 天前
Linux Shell 函数:从定义到实战,让脚本更高效
linux·运维·chrome·shell
isyangli_blog1 天前
(6)数据中心、台式(塔式)服务器、机架式服务器、刀片式服务器
运维·服务器
tq021 天前
Cookie和Seeion在客户端和服务端的角色作用
运维·服务器·安全