2012-05-19 30 views
1

我知道這個問題很多人問我,但我似乎無法找到一個好辦法開始。C# - SSH Winforms仿真控制檯

我一直在使用sharpssh,但它是用於控制檯應用程序的。因此,當我嘗試創建一個winforms應用程序,我不能讓它按我想要的方式運行。

在我的表單中我有: 顯示輸出的文本框 用戶應寫入命令的文本框。

我卡在readline(),我需要暫停應用程序,直到用戶點擊輸入,然後發送插入到文本框中的命令。我不知道如何將應用程序轉換成一個winform應用程序。

所以問題是如何去做這件事? - 我是否應該使用初始化應用程序時啓動的進程,以及在接收到輸出並需要輸入時啓動的進程?然後使用第二個過程來收集在文本框中按下的事件回車鍵的輸入偵聽並啓動另一個過程以發送輸入並再次等待輸出?

如果有,有沒有例子可以解決這個問題?

這是代碼?

public Form1() 
    { 
     InitializeComponent(); 

     txthost.Text = "XXX"; 
     txtuser.Text = "XXXXX"; 
     txtpass.Text = "XXXXX"; 
     string pattern = "sdf:"; 
     mPattern = pattern; 
     this.txtInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(checkforenter); 
    } 

    public void button1_Click(object sender, EventArgs e) 
    { 

     try 
     { 

      mShell = new SshShell(Host, User); 
      mShell.Password = Pass; 
      //WRITING USER MESSAGE 
      txtOutput.AppendText("Connecting..."); 
      mShell.Connect(); 
      txtOutput.AppendText("OK"); 
      //txtOutput.AppendText("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: "); 
      //Stop for user input 

      mShell.ExpectPattern = mPattern; 
      mShell.RemoveTerminalEmulationCharacters = true; 
      _writer = new TextBoxStreamWriter(txtOutput); 

      Console.SetOut(_writer); 

      StringReader reader = new StringReader(txtInput.Text); 

      while (mShell.ShellOpened) 
      { 
       txtOutput.AppendText("\r\n" + "TERMINAL MODE ENGAGED"); 
       txtOutput.AppendText(mShell.Expect(pattern)); 

       txtInput.Text = Console.ReadLine(); 
       Console.ReadLine(); 
       Console.WriteLine(Environment.NewLine); 
       txtOutput.AppendText(mShell.Expect(pattern)); 
       MessageBox.Show("innan enter 2"); 
       Console.WriteLine(Environment.NewLine); 
       txtOutput.AppendText(mShell.Expect(("(continue)"))); 
       MessageBox.Show("efter enter 2"); 
       Console.WriteLine(Environment.NewLine); 
       //Data from termninal --> Append to text 
       string output = mShell.Expect(Pattern); 
       txtOutput.AppendText(output); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

    } 

回答

4

根據在CodeProject上SharpSSH文章(http://www.codeproject.com/Articles/11966/sharpSsh-A-Secure-Shell-SSH-library-for-NET)有兩種方法您可以讀取和寫入SSH連接:

//Writing to the SSH channel 
ssh.Write(command); 

//Reading from the SSH channel 
string response = ssh.ReadResponse(); 

你的文本成爲您的控制檯,這樣你就不必再使用控制檯對象。您需要檢測何時按下Enter鍵。按下時,執行Write命令並將上次輸入的內容發送到SSH連接。然後做一個ReadResponse,它將暫停應用程序並等待響應。一旦它返回,您可以將結果字符串追加到文本框中。

您可能會擔心檢測用戶輸入的內容並將其發送到SSH連接。你可以做的是每次你做一個ReadResponse,得到文本框中的字符索引,然後用它們在字符後按輸入

或者您可以使用兩個文本框,一個用於輸入,另一個用於輸出。

希望這會有所幫助!