使用SSH.NET执行SSH命令无输出问题该如何解决
问题排查及修复方案
- 命令拼接错误:当前代码拼接
check-host和IP参数时没有加空格,会生成无效命令(例如IP为1.1.1.1时会变成check-host1.1.1.1),服务器识别不到合法命令自然不会返回输出。 - 端口变量未定义:代码中实例化
SshClient时用到了port参数,但没有看到该变量的赋值逻辑,若端口值不正确会导致连接异常,无法执行后续命令。 - 未捕获错误流输出:部分命令的运行日志会输出到标准错误流,仅读取
OutputStream会丢失这部分内容。 - UI线程阻塞:所有逻辑直接在按钮点击的UI线程中同步执行,会阻塞UI渲染,导致文本框的内容追加操作要等全部逻辑执行完才会生效,看起来就像没有实时输出。
修正后代码
private void button5_Click(object sender, EventArgs e) { // 把逻辑放到后台线程执行,避免阻塞UI Task.Run(() => { string host = "someserverip"; // 这里补充你的SSH端口定义,默认SSH端口是22 int port = 22; string username = textBox6.Text; string password = textBox8.Text; string ipaddress = textBox12.Text; using (var radius = new SshClient(host, port, username, password)) { radius.Connect(); // 命令和参数之间加空格 var cmd = radius.CreateCommand($"check-host {ipaddress}"); var result = cmd.BeginExecute(); // 同时读取标准输出和标准错误流 using (var outputReader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true)) using (var errorReader = new StreamReader(cmd.ExtendedOutputStream, Encoding.UTF8, true, 1024, true)) { while (!result.IsCompleted || !outputReader.EndOfStream || !errorReader.EndOfStream) { // 读取标准输出 string outputLine = outputReader.ReadLine(); if (outputLine != null) { textBox10.Invoke((Action)(() => textBox10.AppendText(outputLine + Environment.NewLine))); } // 读取错误输出 string errorLine = errorReader.ReadLine(); if (errorLine != null) { textBox10.Invoke((Action)(() => textBox10.AppendText($"[错误] {errorLine}" + Environment.NewLine))); } } } cmd.EndExecute(result); } textBox10.Invoke((Action)(() => textBox10.ScrollBars = ScrollBars.Vertical)); }); }
内容的提问来源于stack exchange,提问作者Patryk Trzaska
相关产品推荐
相关产品推荐

