SSHTools (j2ssh) - Java SSH/SFTP Library
This post is partly for my benefit (so I can find it next time I need it) but mainly because there seems to be a severe lack of information about SFTP/SSH libraries for Java.
I found myself needing to perform the simple (looking) task of sending a file to an FTP site, after writing the code using the org.apache.commons.net.ftp library I quickly discovered I needed to use SFTP rather than FTP. “Simple” I thought, “there must be something like this on the apache site”. Hmmm nothing there, lets try Google.
Commercial
- Loads of options but at $1500+ for a company license a little more than we wanted to pay
Free
- JSch - http://www.jcraft.com/jsch/
- SSHTools - http://sourceforge.net/projects/sshtools/ (used to be j2ssh
Hacky
- Use the psftp.exe program that ships with Putty (I really didn’t want to have to do this)
I took a look at the JSch code and was fairly horrified at the code quality and the random dependencies on Swing and AWT, SSHTools looked a much better option in that the code seems of a far higher quality and well designed, the only downside was it seemed to have been neglected for around 3 years but it’s been recently revived by Chris Thomas and there have been a couple of releases this year.
Anyway after reading the doco (pretty good all in all) I came up with the following snippet
SshClient ssh = new SshClient();
ssh.connect(host, port);
//Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(userName);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
throw new FTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");
}
//Open the SFTP channel
SftpClient client = ssh.openSftpClient();
//Send the file
client.put(filePath);
//disconnect
client.quit();
ssh.disconnect();
Nice and simple, just the way I like it!









Recent Comments