Java ssh使用JSch连接密钥 - Auth Failed

时间:2015-07-29 14:42:20

标签: java authentication ssh jsch ssh-keys

我尝试使用带有密钥的ssh连接到localhost,但我仍然得到" Auth Failed"错误。

以下是方法实现:

public void downloadUsingPublicKey(String username, String host)
    {

         String privateKey = "~/.ssh/id_rsa";

         JSch jsch = new JSch(); 
         Session session = null; 
         Channel channel = null; 
         ChannelSftp channelSftp = null; 
         try 
         { 

             jsch.addIdentity(privateKey); 
             System.out.println("Private Key Added."); 


             session = jsch.getSession(username, host); 
             System.out.println("session created."); 

             java.util.Properties config = new java.util.Properties(); 
             config.put("StrictHostKeyChecking", "no"); 

             session.setConfig(config); 
             session.connect(); 

             channel = session.openChannel("sftp"); 
             channel.connect(); System.out.println("shell channel connected...."); 

             channelSftp = (ChannelSftp)channel; 
             channelSftp.cd(Config.dir); 

             System.out.println("Changed the directory..."); 
         } catch (JSchException e) 
         { 
             // TODO Auto-generated catch block 
             e.printStackTrace(); 
         } catch (SftpException e) 
         { 
             // TODO Auto-generated catch block 
             e.printStackTrace(); 
         }finally
         { 
             if(channelSftp!=null)
             { 
                 channelSftp.disconnect(); 
                 channelSftp.exit(); 
             } 
             if(channel!=null) channel.disconnect(); 
             if(session!=null) session.disconnect(); 
         } 
    }

我使用linux终端创建了我的公钥/私钥对,如下所示:

ssh-keygen -t rsa -b 4096 -C "myemail@email.com"

我没有说任何一句话。 下一步:

ssh-add ~/.ssh/id_rsa

最后

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

然后,当我运行我的程序时,我收到错误:

com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:512)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at pl.eroj.filedownloader.Downloader.downloadUsingPublicKey(Downloader.java:73)
    at pl.eroj.filedownloader.Downloader.main(Downloader.java:107)

有什么想法吗?我的关键是OpenSSH类型从行开始 " -----开始RSA私钥-----"

0 个答案:

没有答案