2010-06-18 84 views
26

如何連接到Java中的SSH服務器?我不需要/需要一個shell。我只想連接到SSH服務器並獲取file.txt的內容。我怎樣才能做到這一點?與Java的SSH連接

回答

5

Java不支持原生地,但你可以使用庫像JSch

1

您必須使用第三方庫 - JSch就是其中之一。谷歌與「Java ssh」,你會得到很多其他選項。

1

您可以檢查JSSH,它是一個Java SSH庫。

1

http://www.ganymed.ethz.ch/ssh2/在Java中實現了ssh2客戶端。我用它來進行端口轉發。

+0

工作,我寧願人們不要使用Ganymed,因爲它不再保持。 – timonti 2013-09-16 11:14:39

+0

@timonti因爲你是維護者? – 2013-09-16 11:37:50

+0

「請注意:蘇黎世聯邦理工學院不再維護代碼,如果您需要更新,請訪問以下網站code.google.com/p/ganymed-ssh-2/」 – 2016-08-14 13:45:12

32

使用JSch

import com.jcraft.jsch.ChannelSftp; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.Session; 
import java.io.*; 

/** 
* 
* @author World 
*/ 
public class SSHReadFile 
    { 
    public static void main(String args[]) 
    { 
    String user = "john"; 
    String password = "mypassword"; 
    String host = "192.168.100.23"; 
    int port=22; 

    String remoteFile="/home/john/test.txt"; 

    try 
     { 
     JSch jsch = new JSch(); 
     Session session = jsch.getSession(user, host, port); 
      session.setPassword(password); 
      session.setConfig("StrictHostKeyChecking", "no"); 
     System.out.println("Establishing Connection..."); 
     session.connect(); 
      System.out.println("Connection established."); 
     System.out.println("Crating SFTP Channel."); 
     ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); 
     sftpChannel.connect(); 
     System.out.println("SFTP Channel created."); 


     InputStream out= null; 
     out= sftpChannel.get(remoteFile); 
     BufferedReader br = new BufferedReader(new InputStreamReader(out)); 
     String line; 
     while ((line = br.readLine()) != null) 
      System.out.println(line); 
     br.close(); 
     } 
    catch(Exception e){System.err.print(e);} 
    } 
    } 

輸出:

Establishing Connection... 
Connection established. 
Crating SFTP Channel. 
SFTP Channel created. 
This is content from file /home/john/test.txt 
+0

偉大的答案爲我工作,但只是使一定要關閉你打開的所有東西。 session.disconnect和sftpChannel.quit。 – 2015-12-16 19:49:51

+0

當調用構造函數時,引發以下異常:'GRAVE:JSF1073:se ha interceptado javax.faces.event.AbortProcessingException durante el procesamiento de INVOKE_APPLICATION 5:UIComponent-ClientId = tipoMovimientoGrid:j_idt15,Mensaje = java.lang.ClassCircularityError:com/jcraft/jsch/JSchException java.lang.ClassCircularityError:com/jcraft/jsch/JSchException \t at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:178)' – Mauro 2016-08-24 17:53:58

+0

嘗試連接Windows Server時出錯: com.jcraft.jsch.JSchException:java.net.ConnectException:連接被拒絕:連接 – 2017-10-03 11:31:10

-1

我用這對我來說

Channel channel=session.openChannel("exec"); 
String command = "Your Command here"; 
((ChannelExec)channel).setCommand(command); 

InputStream in=channel.getInputStream(); 
((ChannelExec)channel).setErrStream(System.err); 
channel.connect();