2015-04-30 61 views
0

我想在C#中創建交互式SSH客戶端會話。我正在使用Renci.SshNet庫來完成此操作。爲了獲得概念證明,我只關心連接到服務器,運行「ls」命令,並檢索當前目錄中的文件夾列表。使用SshNet從遠程服務器(SSH交互式客戶端)檢索文件夾列表

我已經能夠做到這一點,但是,我得到(我相信)服務器域在我的輸出以及文件名。我在底部提供了一張圖片,以顯示我所得到的結果。我不知道如何解析這個....或者我甚至以正確的方式做這個?我已經提供了我的代碼,輸出的圖片以及我希望輸出的內容。

// using.... 
using Renci.SshNet; 

class Program 
{ 
    private const String NEWLINE = "\n"; 
    private bool connected = false; 
    static void Main(string[] args) 
    { 
     Console.Write("Enter hostname: "); 
     String hostname = Console.ReadLine(); 
     Console.Write("Enter username: "); 
     String username = Console.ReadLine(); 
     Console.Write("Enter password: "); 
     String password = Console.ReadLine(); 


     PasswordAuthenticationMethod pw = new PasswordAuthenticationMethod(username, password); 
     ConnectionInfo ci = new ConnectionInfo(hostname, username, pw); 
     SshClient ssh = new SshClient(ci); 

     Console.Write("-Connecting...\n"); 
     ssh.Connect(); 

     IDictionary<Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary<Renci.SshNet.Common.TerminalModes, uint>(); 
     termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53); 
     ShellStream shellStream = ssh.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp); 

     String line = null; 
     String s = null; 

     TimeSpan timeout = new TimeSpan(0, 0, 1); 
     while ((s = shellStream.ReadLine(timeout)) != null) 
     { 
      Console.WriteLine(s); 
     } 
     shellStream.Flush(); 

     while((line = Console.ReadLine()) != "exit") 
     { 
      shellStream.Write(line); 
      shellStream.Write(NEWLINE); 

      while ((s = shellStream.ReadLine(timeout)) != null) 
      { 
       Console.WriteLine(s); 
      } 
      shellStream.Flush(); 
     } 
     Console.Write("Press any key to continue..."); 
     Console.ReadLine(); 
    } 
} 

輸出:

(我強調,我感興趣的是得到的部分)

enter image description here

預期輸出:

- Connecting... 
Last login: Thu Apr 30 10:28:12 2015 from ... 
ls  (user input) 
    2015-03-18_0 
    First_HFSS_Test 
    First_Test 
    ... 

編輯

當我使用「dir」而不是「ls」時,我得到沒有其他信息的目錄列表。我相信「ls」會給我提供顏色信息的列表。也許目錄列表以外的信息是已經被翻譯過的顏色數據?

回答

1

這些是ANSI Escape Sequences,不僅用於編碼顏色指令,但有時用於指定光標移動和繪製區域。

由於a terminal is not a shell您正在收到交互控制代碼。 shell在輸出決定時考慮終端,你的解決方案可能在禁用別名(實際上是它們的參數)。 This answer建議使用/ bin/ls的完整路徑,引用「ls」'ls',反斜槓\ ls或使用命令替換:$(which ls)。

還要注意上面的鏈接答案的註釋:可能需要輸出重定向,以便命令不會截斷它們的輸出,因爲它們適應封閉終端的窗口大小。這有點複雜,但也應該完成工作。

相關問題