如何使用与Java的公私密钥认证使用SFTP例如可靠(Reliable example of how

2019-07-30 02:55发布

最近我们意外地在客户端从FTP到SFTP服务器转移我们收集了一些重要文件。 起初,我的印象是,这将是简单的编写或找到一个java工具,可以处理SFTP下,这绝对不是证明是如此。 什么也加剧了这一问题,我们正在试图连接到从Windows平台的SFTP服务器(这样的地方SSH_HOME是在客户端上的定义变得非常混乱)。

我一直在使用Apache的公地VFS库,并已成功地获取可靠地适用于用户名/密码认证的解决方案,但至今没有什么能够可靠地处理私有/公共密钥认证。

下面的示例适用于用户名/密码认证,但我想调整它的私有/公共密钥认证。

public static void sftpGetFile(String server, String userName,String password, 
        String remoteDir, String localDir, String fileNameRegex)
    {

       File localDirFile  = new File(localDir);
       FileSystemManager fsManager = null;

       if (!localDirFile.exists()) {
           localDirFile.mkdirs();
       }

       try {
           fsManager = VFS.getManager();
       } catch (FileSystemException ex) {
           LOGGER.error("Failed to get fsManager from VFS",ex);
           throw new RuntimeException("Failed to get fsManager from VFS", ex);
       }

       UserAuthenticator auth = new StaticUserAuthenticator(null, userName,password);

       FileSystemOptions opts = new FileSystemOptions();

       try {
           DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts,
                   auth);
       } catch (FileSystemException ex) {
           LOGGER.error("setUserAuthenticator failed", ex);
           throw new RuntimeException("setUserAuthenticator failed", ex);
       }
       Pattern filePattern = Pattern.compile(fileNameRegex);
       String startPath = "sftp://" + server + remoteDir;
       FileObject[] children;

       // Set starting path on remote SFTP server.
       FileObject sftpFile;
       try {
           sftpFile = fsManager.resolveFile(startPath, opts);

           LOGGER.info("SFTP connection successfully established to " +
                   startPath);
       } catch (FileSystemException ex) {
           LOGGER.error("SFTP error parsing path " +
                   remoteDir,
                   ex);

           throw new RuntimeException("SFTP error parsing path " +
                   remoteDir,
                   ex);
       }

       // Get a directory listing
       try {
           children = sftpFile.getChildren();
       } catch (FileSystemException ex) {
           throw new RuntimeException("Error collecting directory listing of " +
                   startPath, ex);
       }

       search:
       for (FileObject f : children) {
           try {
               String relativePath =
                       File.separatorChar + f.getName().getBaseName();

               if (f.getType() == FileType.FILE) {
                   System.out.println("Examining remote file " + f.getName());

                   if (!filePattern.matcher(f.getName().getPath()).matches()) {
                       LOGGER.info("  Filename does not match, skipping file ." +
                               relativePath);
                       continue search;
                   }

                   String localUrl = "file://" + localDir + relativePath;
                   String standardPath = localDir + relativePath;
                   System.out.println("  Standard local path is " + standardPath);
                   LocalFile localFile =
                           (LocalFile) fsManager.resolveFile(localUrl);
                   System.out.println("    Resolved local file name: " +
                           localFile.getName());

                   if (!localFile.getParent().exists()) {
                       localFile.getParent().createFolder();
                   }

                   System.out.println("  ### Retrieving file ###");
                   localFile.copyFrom(f,
                           new AllFileSelector());
               } else {
                   System.out.println("Ignoring non-file " + f.getName());
               }
           } catch (FileSystemException ex) {
               throw new RuntimeException("Error getting file type for " +
                       f.getName(), ex);
           }

       }

       FileSystem fs = null;
       if (children.length > 0) {
           fs = children[0].getFileSystem(); // This works even if the src is closed.
           fsManager.closeFileSystem(fs);
       }
    }

我有我存储在一个已知位置的私钥和我的公钥已经distrubuted到服务器(我们已经测试了这些键使用其他工具进行连接时,工作成功地)

我已经打得四处添加以下行

SftpFileSystemConfigBuilder.getInstance().setIdentities(this.opts, new File[]{new File("c:/Users/bobtbuilder/.ssh/id_dsa.ppk")});

这成功地加载私钥到整个框架,但它永远不会再使用该密钥来进一步验证。

任何帮助或方向最热情接待

Answer 1:

很多周围挖后,我终于得到了自己的答案。 看来,很多我的麻烦是与私营部门和公共密钥的格式做

专用密钥必须是OpenSSH格式公钥无论出于何种原因,只能从窗户的puttygen粘贴(出口公钥似乎总是缺少头意味着freeSSHD窗口服务器无法用它来给它)

总之下面是我的代码,我终于与包括的javadoc来了,所以希望可以省些别人我所经历的痛苦

/**
* Fetches a file from a remote sftp server and copies it to a local file location.  The authentication method used
* is public/private key authentication. <br><br>

* IMPORTANT: Your private key must be in the OpenSSH format, also it must not have a passphrase associated with it.
*    (currently the apache-commons-vfs2 library does not support passphrases)<p>
* 
* Also remember your public key needs to be on the sftp server.  If you were connecting as user 'bob' then your
* public key will need to be in '.ssh/bob' on the server (the location of .ssh will change depending on the type
* of sftp server)
* 
* @param server The server we care connection to 
* @param userName The username we are connection as
* @param openSSHPrivateKey The location of the  private key (which must be in openSSH format) on the local machine
* @param remoteDir The directory from where you want to retrieve the file on the remote machine (this is in reference to SSH_HOME, SSH_HOME is the direcory you 
* automatically get directed to when connecting)
* @param remoteFile The name of the file on the remote machine to be collected (does not support wild cards)
* @param localDir The direcoty on the local machine where you want the file to be copied to
* @param localFileName The name you wish to give to retrieved file on the local machine
* @throws IOException - Gets thrown is there is any problem fetching the file
*/
public static void sftpGetFile_keyAuthentication(String server, String userName, String openSSHPrivateKey,
    String remoteDir,String remoteFile, String localDir, String localFileName) throws IOException
{

   FileSystemOptions fsOptions = new FileSystemOptions();
   FileSystemManager fsManager = null;
   String remoteURL = "sftp://" + userName + "@" + server + "/" + remoteDir + "/" + remoteFile;
   String localURL  = "file://" + localDir + "/" + localFileName;

    try {
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
        SftpFileSystemConfigBuilder.getInstance().setIdentities(fsOptions, new File[]{new File(openSSHPrivateKey)});
        fsManager = VFS.getManager();
        FileObject remoteFileObject = fsManager.resolveFile(remoteURL, fsOptions);
        LocalFile localFile =
                   (LocalFile) fsManager.resolveFile(localURL);
        localFile.copyFrom(remoteFileObject,
                   new AllFileSelector());
    } catch (FileSystemException e) {
        LOGGER.error("Problem retrieving from " + remoteURL + " to " + localURL,e );
        throw new IOException(e);
    }
}


Answer 2:

这篇文章,答案是非常有益的,非常感谢你。

我只想集成添加到声明“ 目前Apache的公地VFS2库不支持密码短语 ”,因为我与密码做的还和它的工作。

你必须导入jsch库项目(我用0.1.49)和实现接口“com.jcraft.jsch.UserInfo”。

像这样的东西应该是罚款:

public class SftpUserInfo implements UserInfo {

    public String getPassphrase() {
        return "yourpassphrase";
    }

    public String getPassword() {
        return null;
    }

    public boolean promptPassphrase(String arg0) {
        return true;
    }

    public boolean promptPassword(String arg0) {
        return false;
    }
}

然后你就可以将其添加到SftpFileSystemConfigBuilder是这样的:

SftpFileSystemConfigBuilder.getInstance().setUserInfo(fsOptions, new SftpUserInfo());

希望这可以帮助。



Answer 3:

我想这是你在找什么 -

/**
* @param args
*/
public static void main(String[] args) {

    /*Below we have declared and defined the SFTP HOST, PORT, USER
            and Local private key from where you will make connection */
    String SFTPHOST = "10.20.30.40";
    int    SFTPPORT = 22;
    String SFTPUSER = "kodehelp";
    // this file can be id_rsa or id_dsa based on which algorithm is used to create the key
    String privateKey = "/home/kodehelp/.ssh/id_rsa";
    String SFTPWORKINGDIR = "/home/kodehelp/";

    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(SFTPUSER,SFTPHOST,SFTPPORT);
        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(SFTPWORKINGDIR);
        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();
    }
}

更多信息请访问

http://kodehelp.com/sftp-connection-public-key-authentication-java/



文章来源: Reliable example of how to use SFTP using public private key authentication with Java
标签: java sftp