AAH*_*AHN 5 .net c# ssh stream ssh.net
有什么方法可以执行Linux命令并在Windows应用程序(如PuTTY)中的文本框中显示结果。
例如,我正在尝试执行以下命令
wget http://centos-webpanel.com/cwp-latest
sh cwp-latest
Run Code Online (Sandbox Code Playgroud)
使用以下代码
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");
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
该命令需要花费一定的时间才能执行,并且结果文本框中没有显示任何结果。
首先,除非有充分的理由,否则不要使用“ shell”通道来自动执行命令。使用“ exec”通道(CreateCommand或RunCommand在SSH.NET中)。
要将输出提供给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);
}
}
Run Code Online (Sandbox Code Playgroud)
对于稍微不同的方法,请参见类似的WPF问题:
SSH.NET实时命令输出监视。
以这种方式执行时,某些程序(例如Python)可能会缓冲输出。请参阅:
如何从本地控制台上以C#SSH.NET执行的远程主机(Raspberry Pi)上运行的Python程序连续写入输出?
| 归档时间: |
|
| 查看次数: |
6643 次 |
| 最近记录: |