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



    }
}
相关推荐
shaoing13 小时前
OpenSSH 一键升级到 10.3p1 完整教程(源码编译・生产安全)
ssh
有毒的教程20 小时前
Ubuntu 虚拟机磁盘空间不足完整解决教程
linux·运维·ubuntu
geNE GENT20 小时前
Nginx WebSocket 长连接及数据容量配置
运维·websocket·nginx
Cx330❀1 天前
一文吃透Linux System V共享内存:原理+实操+避坑指南
大数据·linux·运维·服务器·人工智能
薛定谔的悦1 天前
储能系统(EMS)核心架构解析:充放电控制、防逆流、防过载与 PID 调节
linux·运维·架构
志栋智能1 天前
超自动化运维的终极目标:让系统自治运行
运维·网络·人工智能·安全·自动化
阿 才1 天前
WSL2 + TFTP + 网络启动(Linux开发板与WSL2建立网络连接)
linux·运维·网络
Benszen1 天前
Docker容器化技术全解析
运维·docker·容器
IMPYLH1 天前
Linux 的 false 命令
linux·运维·服务器·bash
小江的记录本1 天前
【Linux】《Linux常用命令汇总表》
linux·运维·服务器·前端·windows·后端·macos