Home > Java > using a combination of JSCH and Apache VFS Commons to SFTP with a private key

using a combination of JSCH and Apache VFS Commons to SFTP with a private key


package test.sftp;

import java.io.File;

import org.apache.commons.vfs.AllFileSelector;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.FileSystemOptions;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.provider.sftp.SftpFileSystemConfigBuilder;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

public class SFTPTest {

public static void main(String[] args) throws JSchException, SftpException,
FileSystemException {

FileSystemOptions options = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(options, "no");
File keyFile = new File("path/to/the/private/key.ppk");
SftpFileSystemConfigBuilder.getInstance().setIdentities(options, new File[] { keyFile });
SftpFileSystemConfigBuilder.getInstance().setKnownHosts(options, new File("path/to/known_hosts")); // optional step, usually ~/.ssh/known_hosts

FileSystemManager fsManager = VFS.getManager();
String uri = "sftp://username:password@hostname:22";

FileObject from = fsManager.resolveFile(uri, options);
FileObject to = fsManager.resolveFile("/tmp", options);
to.copyFrom(from, new AllFileSelector());
}
}

Advertisement
Categories: Java Tags: , , , , , , , , ,
  1. No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.