I recently had to use SFTP from a Java application and it did take some source-diving to figure out exactly how it works (specifically to get the parameters for JSch.addIdentity right). It turned out to be rather straight-forward:
...
private void execute() throws JSchException, SftpException {
JSch jSch = new JSch();
final byte[] prvkey = readMyPrivateKeyFromFile(); // Private key must be byte array
final byte[] emptyPassPhrase = new byte[0]; // Empty passphrase for now, get real passphrase from MyUserInfo
jSch.addIdentity(
"myusername", // String userName
prvkey, // byte[] privateKey
null, // byte[] publicKey
emptyPassPhrase // byte[] passPhrase
);
Session session = jSch.getSession("myusername", "hostname.com", 22);
UserInfo ui = new MyUserInfo(); // MyUserInfo implements UserInfo
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("sftp");
ChannelSftp sftp = (ChannelSftp) channel;
sftp.connect();
final Vector files = sftp.ls(".");
for (Object obj : files) {
// Do stuff with files
}
sftp.disconnect();
session.disconnect();
}
...
The MyUserInfo class must implement the UserInfo interface. There are a number of good examples of this in the jsch distribution.