2010-06-18 71 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();