2017-11-20 8 views
2

Linux 명령을 실행하고 PuTTY와 같은 Windows 응용 프로그램의 텍스트 상자에 결과를 표시하는 방법이 있습니까? SSH.NET에서 장시간 명령을 실행하고 텍스트 상자에 결과를 계속 표시하십시오.

예를 들어 다음 코드
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(); 
} 
이 명령은 시간에 따라 소요

가 실행되는

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"); 
를 사용하여 다음 명령

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

을 실행하기 위해 노력하고있어 어떠한 결과가 나타나지 않았다 결과 텍스트 상자에.

답변

2

첫째, 좋은 이유가없는 한 명령 실행을 자동화하기 위해 "쉘"채널을 사용하지 마십시오. "exec"채널을 사용하십시오 (CreateCommand 또는 RunCommand, SSH.NET). 약간 다른 접근 방식의 경우

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 질문을 참조하십시오 :

는 백그라운드 스레드에서 스트림을 읽는 유지하는 TextBox 출력을 공급하려면 SSH.NET real-time command output monitoring합니다.