2010-07-21 231 views
7

是否可以通过java与服务器建立ssh连接?SSH连接Java

+2

检查[http://stackoverflow.com/questions/3071760/ssh-connection-with-java/9019095#9019095] – World 2012-03-08 09:00:56

+0

FWIW,我在那些刚刚看了一下如下所列,并且sshtools仅在GPL许可下可用。 (jsch在BSD下可用,sshJ在Apache下可用。) – Mickalot 2013-05-20 14:46:17

回答

3

jschsshJ都是很好的客户。我个人使用sshJ,因为代码被更彻底地记录下来。

jsch已被广泛使用,包括在eclipse和apache ant中。我也遇到过jsch和AES加密私钥的问题,这些私钥需要在3DES中重新加密,但这可能就是我。

+0

确定jsch库工作正常并且很容易实现。谢谢您的回答。 – Benni 2010-07-22 20:34:53

1

为了连接到Java服务器,你需要一个SSHD的实现(SSH客户端是不够的)。您可以尝试阿帕奇SSHD,

http://mina.apache.org/sshd/

由于sshd的是已经在大多数系统上运行的,更简单的方法是通过SSH隧道来连接到服务器。

2

是的,这是可能的。你可以试试下面的代码:

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

public class SSHReadFile 
    { 
    public static void main(String args[]) 
    { 
    String user = "user"; 
    String password = "password"; 
    String host = "yourhostname"; 
    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."); 
     } 
    catch(Exception e){System.err.print(e);} 
    } 
    } 
+0

完美。为我工作。 – 2014-07-30 06:39:23