2010-03-25 100 views
21

我是新來的這種Java應用程序,並尋找關於如何使用SSH連接到遠程服務器,執行命令以及使用Java作爲編程語言返回輸出的示例代碼。如何在使用Java的遠程系統上運行SSH命令?

+0

我張貼一些代碼,可能幫助:http://stackoverflow.com/questions/2405885/any-good-jsch-examples – 2013-10-26 21:11:57

回答

13

看一看的Runtime.exec()的Javadoc

Process p = Runtime.getRuntime().exec("ssh myhost"); 
PrintStream out = new PrintStream(p.getOutputStream()); 
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 

out.println("ls -l /home/me"); 
while (in.ready()) { 
    String s = in.readLine(); 
    System.out.println(s); 
} 
out.println("exit"); 

p.waitFor(); 
+0

這是否工作?爲什麼給它一個-1? – Zubair 2011-01-06 09:47:02

+1

@Zubair - 給-1的傢伙並沒有打算解釋他的觀點。這個解決方案的確行得通,因爲它只有儘可能簡單。雖然這不是「純Java」,但這是一個缺點,但如果你使用的是Linux,那麼不使用第三方庫就可以簡化它。 – bobah 2011-01-06 16:28:41

+0

好的,謝謝你的解釋 – Zubair 2011-01-06 17:51:15

11

JSch是一個純Java實現SSH2的,可以幫助你運行遠程機器上的命令。 你可以找到它here,並且有一些例子here。您可以使用exec.java

3

你可以看看這個基於Java的框架來執行遠程命令,包括:通過SSH:https://github.com/jkovacic/remote-exec 它依賴於兩個開源的SSH庫,無論是JSch(即使支持ECDSA身份驗證的實現)或Ganymed(這兩個庫中的一個都足夠了)。乍一看,它可能看起來有點複雜,你必須準備大量的SSH相關類(提供服務器和用戶詳細信息,指定加密細節,提供OpenSSH兼容私鑰等,但SSH本身非常複雜太)。另一方面,模塊化設計允許簡單包含更多的SSH庫,輕鬆實現其他命令的輸出處理甚至交互式類等。

2

下面是在java中SSh最簡單的方法。下載任何在下面的鏈接,並提取該文件,然後從提取的文件添加jar文件,並添加到項目 http://www.ganymed.ethz.ch/ssh2/ 的構建路徑,並使用下面的方法

public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{ 
     System.out.println("inside the ssh function"); 
     try 
     { 
      Connection conn = new Connection(serverIp); 
      conn.connect(); 
      boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password); 
      if (isAuthenticated == false) 
       throw new IOException("Authentication failed.");   
      ch.ethz.ssh2.Session sess = conn.openSession(); 
      sess.execCommand(command); 
      InputStream stdout = new StreamGobbler(sess.getStdout()); 
      BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); 
      System.out.println("the output of the command is"); 
      while (true) 
      { 
       String line = br.readLine(); 
       if (line == null) 
        break; 
       System.out.println(line); 
      } 
      System.out.println("ExitCode: " + sess.getExitStatus()); 
      sess.close(); 
      conn.close(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(System.err); 

     } 
    } 
相關問題