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



    }
}
相关推荐
xiaoduo AI3 小时前
智能客服机器人能精准预判用户疑问提前主动应答吗?能大幅缩短客户咨询沟通时长吗?
运维·服务器·机器人
勤劳的进取家3 小时前
服务器文件交互方式
运维·服务器·microsoft
yyuuuzz3 小时前
aws亚马逊云上部署常见问题梳理
运维·服务器·网络·数据库·云计算·aws
优化Henry3 小时前
5G站点光链路降级告警排查与处理——AAS光端口隐性故障定位
运维·网络·5g·信息与通信
wanhengidc3 小时前
算力服务器的优势都有哪些?
大数据·运维·服务器·网络·人工智能·安全·智能手机
bukeyiwanshui4 小时前
20260508 docker教案
运维·docker·容器
King's King4 小时前
自动化立体仓库项目立项申请报告
运维·自动化
xingyuzhisuan4 小时前
风冷还是水冷?RTX 4090服务器散热方案对比
运维·服务器·ai·gpu算力
你今天努力了吗?*—*4 小时前
4.1 Linux 日志排查
linux·运维·服务器
山上三树4 小时前
操作系统如何实现各种功能
linux·运维·服务器