2014-09-29 92 views
1

我試圖實現一個模擬用戶在Java中的ssh控制檯上寫/讀的用戶。 我正在使用JSCH庫來管理ssh連接。 這是從我開始的代碼:如何創建一個模擬SSH shell用戶交互的bot?

JSch jsch = new JSch(); 
Session session = jsch.getSession(username, ipAddress, port); 
session.setPassword(password); 
Properties config = new Properties(); 
config.put("StrictHostKeyChecking", "no"); 
session.setConfig(config); 
session.connect(connectionTimeoutInMillis); 
Channel channel = session.openChannel("shell"); 
InputStream is = new InputStream(); 
OutputStream out= new OutputStream(); 
channel.setInputStream(is); 
channel.setOutputStream(out); 
channel.connect(); 
channel.disconnect(); 
is.close(); 
out.close(); 
session.disconnect(); 

顯然在代碼中InputStreamOutputStream錯了,我需要用的東西,機器人可以用它來發送一個字符串(命令行)和接收一個String(命令執行的結果),我應該使用什麼類型的流來獲取?

此外我注意到,如果我發送一個命令並在很多情況下使用System.out作爲輸出流,則輸出爲空,因爲(我對此幾乎肯定),Java應用程序在命令執行產生結果之前終止。對於JSCH通道監聽器「等到命令執行完成後」告訴什麼是最佳做法,然後繼續?我可以在命令執行後使用Thread.sleep(someTime),但由於顯而易見的原因,我不太喜歡它。

回答

1

考慮使用第三方的Expect-like Java庫來簡化與遠程shell的交互。這裏是一個很好的選項設置,你可以嘗試:

您還可以看看我創造了前一段時間我自己的開源項目作爲現有的繼承者。它被稱爲ExpectIt。我的圖書館的優點在項目主頁上陳述。

以下是使用JSch與公共遠程SSH服務進行交互的示例。應該很容易將它用於您的用例。

JSch jSch = new JSch(); 
    Session session = jSch.getSession("new", "sdf.org"); 
    session.connect(); 
    Channel channel = session.openChannel("shell"); 

    Expect expect = new ExpectBuilder() 
      .withOutput(channel.getOutputStream()) 
      .withInputs(channel.getInputStream(), channel.getExtInputStream()) 
      .withErrorOnTimeout(true) 
      .build(); 
    try { 
     expect.expect(contains("[RETURN]")); 
     expect.sendLine(); 
     String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1); 
     System.out.println("Captured IP: " + ipAddress); 
     expect.expect(contains("login:")); 
     expect.sendLine("new"); 
     expect.expect(contains("(Y/N)")); 
     expect.send("N"); 
     expect.expect(regexp(": $")); 
     expect.send("\b"); 
     expect.expect(regexp("\\(y\\/n\\)")); 
     expect.sendLine("y"); 
     expect.expect(contains("Would you like to sign the guestbook?")); 
     expect.send("n"); 
     expect.expect(contains("[RETURN]")); 
     expect.sendLine(); 
    } finally { 
     session.close(); 
     ssh.close(); 
     expect.close(); 
    } 

這裏是鏈接到完整可行example

相關問題