Sunday 12 December 2010

JSch, SFTP and Zlib compression

JSch is a superb library which I recommend for your Java SSH stuff.  Unfortunately the documentation is not good.  There's virtually nothing apart from the example programs in the distribution.  It sometimes takes a while to figure things out, so here's how I implemented SFTP client with Zlib compression (disclaimer: exception handling/structure removed for clarity):
JSch jsch = new JSch();

// configure to attempt zlib compression first, fallback to no compression if unsuccessful
java.util.Properties config = new java.util.Properties();
config.put("compression.s2c", "zlib,none");
config.put("compression.c2s", "zlib,none");
config.put("StrictHostKeyChecking", "no");

Session session = jsch.getSession(sftpUserName, sftpIP, sftpPort);
session.setPassword(sftpPassword);
session.setConfig(config);
session.connect(CONNECTION_TIMEOUT);

ChannelSftp channel = session.openChannel("sftp");

channel.connect();
ChannelSftp c = (ChannelSftp) channel;

// do whatever required

channel.disconnect();

session.disconnect();
Do not forget to put JZlib in your classpath!

What if you'd rather use SSH key authentication (instead of, or as well as, a password)?  Put this just after the first line:
jsch.addIdentity("<path to private key file>", "passphrase");
PuTTYgen is a nice windows tool for generating SSH key pairs.  It's likely you'll want to export in OpenSSH format (Conversions->Export OpenSSH key), but it will depend on the format your server is expecting.