gpt4 book ai didi

c# - 在 SSH.NET 中执行长时间命令并在 TextBox 中连续显示结果

转载 作者:太空狗 更新时间:2023-10-29 22:35:49 35 4
gpt4 key购买 nike

有没有办法在像PuTTY这样的Windows应用程序中执行Linux命令并在文本框中显示结果。

例如我正在尝试执行以下命令

wget http://centos-webpanel.com/cwp-latest
sh cwp-latest

使用下面的代码

SshClient sshclient = new SshClient(IPtxtBox.Text, UserNameTxt.Text, PasswordTxt.Text);
sshclient.Connect();
ShellStream stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);

resultTxt.Text = SSHCommand.SendCommand(stream, "wget http://centos-webpanel.com/cwp-latest && sh cwp-latest");
private static void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
{
writer.WriteLine(cmd);
while (stream.Length == 0)
Thread.Sleep(500);
}
private static string ReadStream(StreamReader reader)
{
StringBuilder result = new StringBuilder();

string line;
while ((line = reader.ReadLine()) != null)
result.AppendLine(line);

return result.ToString();
}
private static string SendCommand(ShellStream stream, string customCMD)
{
StringBuilder strAnswer = new StringBuilder();

var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
WriteStream(customCMD, writer, stream);

strAnswer.AppendLine(ReadStream(reader));

string answer = strAnswer.ToString();
return answer.Trim();
}

该命令执行时间较长,结果文本框未显示结果。

最佳答案

首先,除非你有充分的理由,否则不要使用“shell” channel 自动执行命令。使用“执行” channel (SSH.NET 中的 CreateCommandRunCommand)。

要将输出提供给 TextBox,只需在后台线程上继续读取流即可:

private void button1_Click(object sender, EventArgs e)
{
new Task(() => RunCommand()).Start();
}

private void RunCommand()
{
var host = "hostname";
var username = "username";
var password = "password";

using (var client = new SshClient(host, username, password))
{
client.Connect();
// If the command2 depend on an environment modified by command1,
// execute them like this.
// If not, use separate CreateCommand calls.
var cmd = client.CreateCommand("command1; command2");

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)
{
textBox1.Invoke(
(MethodInvoker)(() =>
textBox1.AppendText(line + Environment.NewLine)));
}
}
}

cmd.EndExecute(result);
}
}

对于稍微不同的方法,请参阅类似的 WPF 问题:
SSH.NET real-time command output monitoring .

以这种方式执行时,某些程序(如 Python)可能会缓冲输出。参见:
How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console?

关于c# - 在 SSH.NET 中执行长时间命令并在 TextBox 中连续显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47386713/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com