Skip to content


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

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!

Posted in /Technology. Tagged with .

64 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. John said

    Ah, something I almost know about.

    The thing is, SFTP is not FTP. Although it wasn’t dishonest of the SSH team to call their file transfer protocol “SSH File Transfer Protocol”, it does cause an awful lot of confusion, especially when the real secure FTP is called FTPS.

    It’s best *never* to refer to SFTP as FTP, as it perpetuates the confusion (so change the name of your FTPException).

    Anyhow, it looks like a nice clean API you’ve found. I do hope that client.put() has a return code or throws an exception, though — and you should be checking or catching it.

  2. That’s a good point on FTPException, I’ll rename it (it’s a hangover from the original FTP version I wrote). The confusion between FTPS and SFTP is pretty annoying, it took me a while to work out which the site was using. The put call does throw exceptions (IOException) which I catch, log, email (if possible) and then terminate the application. On a related note using Java again has got me thinking about Checked vs Unchecked exceptions. I still can’t really decide which I prefer.

  3. This is fantastic! I’ve been googling as well, trying to find a decent library. I was the same as you…. as popular as SSH and Java are, surely it would be an easy find.

    Thanks for the post! I can really use this in my job!

    Aaron

  4. thanks. i wanted this thing and i got it here. i would love it if you provide some detailed description as well.

  5. CDW said

    thank you.

  6. Neville said

    Is there a way to provide multiple commands in a single ssh session using j2ssh. please mail me …. :(

  7. Roshan said

    where i can find j2ssh. do i need to install this?

  8. Roshan said

    Hi Any one Please help me to get the com.sshtools.j2ssh package …

    Thank you

  9. Roshan, the links are in the blog post, I think http://sourceforge.net/projects/sshtools/ is what you’re looking for
    Dave

  10. Roshan said

    Thanx Dave,
    i got it.. :-)

  11. LS said

    Hi,
    I’ve tried your above example however i’m not able to connect to the sftp server.

    I can manually loging via ssh and sftp, so i know the access is there. The error i keep getting is:
    com.sshtools.j2ssh.transport.TransportProtocolCommon: Sending SSH_MSG_USERAUTH_REQUEST

    [Transport protocol 1] com.sshtools.j2ssh.transport.TransportProtocolCommon: Received SSH_MSG_USERAUTH_FAILURE

    Result 2

    I was wondering if i needed to do anything additional?

  12. venky said

    Hey for sftpclient .. i didnt find any method to get the file
    from remote location. all i am seeing is copying to local and
    get from the local path. so i dont want anything in my local.
    So is there any way i get can get file as bytes or file from get method ?

  13. Ashwin said

    Hey thnx a lot Dave, I was just looking at JSch and accidentally stumbled upon this article.

    I totally agree with your point on JSch, thnx again for putting me to the correct library

  14. I get a null pointer exception with sftp.put() when the file I am uploading is about 80KB. I reduced the file size and it works. I am using version 0.2.9. Any suggestions ?

  15. Vikas said

    I too am working on a similiar requirement. JSch is a good option incase if you are working with SSH2. JSch does not work with SSH1 so becareful while choosing the library.

    As far as swing component in JSch is considered, we can surely decouple it from the core API.

  16. Maxime said

    This is exactly what I needed for my project. Thank you very much.

    Maxime – France

  17. nanoj said

    I would like to use a ssh client within java if i use the above code Do i need to use the sshtools
    I have used the Telnet client to connect but i now want to replace it to use the ssh client .

    import org.apache.commons.net.telnet.TelnetClient;

    What do i need to download to use the above sniipet of code .
    Thanks in adavance .

  18. nanoj:- The links to the downloads are all in the post
    Dave

  19. Nami said

    When ever I am trying to connect to a remote server using SFTP, am getting error message .. “SFTP Subsystem could not be initialized”. The remote SSH server is up and run. When I tried to connect to the remote server thru SSH Secure Shell, I was able to connect. But not thru the class which implemented the SFTP. Any body faced this problem ?

  20. Marco said

    Has anybody tried Trilead SSH for Java http://www.trilead.com/Products/Trilead_SSH_for_Java/ ?

  21. Minlang said

    tail -f test.sh

    after i execute the above command, how do i know this is still running before i press Ctrl+C to interrupt it?
    i mean no console display but just run background.

    seems session.getInputStream().available() not work.

    any suggestion?

  22. Chung said

    How to upload the file to remote machine by copying the file’s full permission and access time?
    I don’t see any method to include the -P flag when transfer file.

    Any option I can do this?
    Please help..

  23. kat said

    Hi,

    I couldn’t find the SshClient class.
    How did you get that ?
    and there is no docs and only some complex examples.

    can anyone help ??

    it’s urgent

  24. Mike Kares said

    The class is located at:

    import com.sshtools.j2ssh.SshClient

    If you download the source, there are a few easy to follow examples located in the j2ssh/examples folder.

    I was able to get this up and running in my application in a very short amount of time (basically ssh to a web server, then upload some files that my app dynamically creates).

    BTW, there is some documentation in the form of javadocs, but that appears to be for an older version, so I don’t know how useful that will be.

  25. Vikram chauhan said

    Hi All,
    i am using JSCH for last one year and not found any problem there . I am using it for SFTP and SSH client instead of telnet.

    I am very setisfied with it . its having some swing componet dependices but we can easily remove from the source code or can be make our own ssh client with the help of there examples

  26. ghost_kd said

    Hi,
    I have use it. Nice tool.
    I’m having some issues with handling session data.
    I am unable to get data from ssh prompt. i.e I want to get output of “ls” in my program. It didn’t gave any error. But, no data.
    I followed the document(j2ssh-getting-started.htm -> handling session data). But did’t work.
    Can some please help?

    Regards,
    KD

  27. ghost_kd said

    Never Mind. it worked.

  28. ghost_kd said

    Hi,

    Can I execute multiple commands with single authentication?
    i.e. I made connection and want to execute 10 commands on that ssh.
    I read the getting started where it’s mentioned that you can run multiple commands by creating new instance of SessionChannelClient for each command.
    I tried that but it’s not working. Can someone help please?

  29. Arindam Roy said

    One thing worth noting is that the latest source code uses Java 5 libraries, for e.g java.util.concurrent.ConcurrentHashMap. Hence it can’t be used with JDK 1.4.

  30. Gopi said

    Hi,
    I wrote a simple java application (similar connection code as above) which uses J2SSH to make SSH connection and authenticates the connection using Public Key method. when the java application is started it could not able to make the SSH connection and ends up in the exception below

    .
    .
    .
    - Loading supported cipher algorithms
    - Loading key exchange methods
    - Loading compression methods
    - Loading message authentication methods
    - Starting transport protocol
    - Registering transport protocol messages with inputstream
    - The Transport Protocol thread failed; terminating it.
    com.sshtools.j2ssh.SshException: Unable to communicate via SSH.
    at com.sshtools.j2ssh.transport.TransportProtocolCommon.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: com.sshtools.j2ssh.transport.AlgorithmNotSupportedException: DH KeyPairGenerator not available
    at com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.onInit(Unknown Source)
    at com.sshtools.j2ssh.transport.kex.SshKeyExchange.init(Unknown Source)
    … 2 more

    I could not determine why the above exception is occurred, did any one came across the same exception? it will be a great help if you can share your thoughts in solving the problem…

    the exception is raised when SshClient.connet(..) method is invoked..

    Thank you

  31. Abhishek Rathore said

    Hi, I am able to use sftp using above code, wherin we authenticate using userid and password, but in my company security team is not agreeing to tell us password rather they have implemented ssh key between two machines so that password is not required while connecting to remote machine.
    Does anyone know how to do sftp without knowing passord(ssh key has been implemented between source and destination machine).
    I will appreciate a quick and precise response.

  32. l said

    I am having some difficulties getting the sample code to execute. I downloaded all the files and successfully built the project using ant. However, when i try to instantiate the SshClient class SshClient c = new SshClient(); I get the following exception.
    Exception in thread “AWT-EventQueue-0″ java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at com.sshtools.j2ssh.SshClient.(Unknown Source)

  33. Praveen said

    Abhishek, Look more into HostKeyVerification class. Here I ignored but i think you can create the host key and connect.

    SshClient ssh = new SshClient();
    HostKeyVerification hostKey = new IgnoreHostKeyVerification();
    ssh.connect(host, port, hostKey);

  34. Vikram said

    Hi
    i am getting following exception at line
    SftpClient sftp = ssh.openSftpClient();

    Exception in thread “main” java.io.IOException: The message store has reached EOF
    at com.sshtools.j2ssh.connection.ConnectionProtocol.openChannel(ConnectionProtocol.java:200)
    at com.sshtools.j2ssh.SshClient.openChannel(SshClient.java:1301)
    at com.sshtools.j2ssh.SshClient.openSftpChannel(SshClient.java:1255)
    at com.sshtools.j2ssh.SftpClient.(SftpClient.java:95)
    at com.sshtools.j2ssh.SshClient.openSftpClient(SshClient.java:1131)
    at com.sshtools.j2ssh.SshClient.openSftpClient(SshClient.java:1114)
    at test.SFTPTest.main(SFTPTest.java:65)

  35. hvu said

    sweet. thank you for the post. you’ve just saved me a couple of days.

  36. Mukta Jindal said

    Thanks for this simple and working code for SFTP !!!

  37. edtFTPj/PRO uses j2ssh under the covers. It’s a commercial product but pretty affordable (from $499). In the last few years we’ve fixed loads of bugs in j2ssh code. An added bonus – edtFTPj/PRO supports FTP and FTPS, all with the same common interface making it easy to switch protocols. See http://www.enterprisedt.com/products/edtftpjssl/overview.html for a trial download.

  38. Bill said

    Thanks for pointing me in the right direction!

  39. Matt said

    Hi all, I am having difficulty getting authenticated using this example. I am able to use WinSCP to connect via SFTP to a server using a host,port,user name and password, but when i use the same credentials using the client example above I get a “failed to authenticate” error.
    Any help would be greatly appreicated!!
    Feel ffree to email me at matt.michaud@rosetta.com
    Thanks

  40. Dick said

    Dave,

    Your example was excellent! I was able to write a put example as well that works great. This is so much better than writing some cludgey script.

    Thanks

    Dick

  41. Srikanth said

    Hi all, I am having difficulty connecting to SFTP server. I am able to connect to SFTP using WinSCP using host,port,user name and password. But when I tried the same in java app, getting the error “INFO: The host key signature is invalid
    IOException”
    Any help would be greatly appreicated!!
    Thanks

  42. Enzo said

    Hi all, anyone cuold execute a command throw a sshclient connection? because I couldnt… Please if anybody have the correct code to for example execute an “ls -l” and get the output of the command it would be great for me. Thanks!!!

  43. bigjavageek said

    There is this SFTP Java API from http://www.zehon.com . I like it, it’s free, easy to use.

  44. obako said

    can somone tell me why i cant use setUsername method, setPwrd works just fine but setUser shows as error….and its pissing me off couze in every example i found it was used…any ideas folks?

  45. anony said

    I am searching for a open source SSH2 Java based server APIs. I browsed through the J2SSH but that seems like a client code. any suggestions on where to find Java ssh2 server based code. please help

  46. Ashok kumar said

    Hi all,

    I tried to use the example program SftpConnect.java. I am getting a confirmation message like this
    ‘The host ‘xxx’ is currently unknown to the system
    The host key fingerprint is: 1024: ds fd sd fd
    Do you want to allow this host key? [Yes|No|Always]:’

    How to get rid off this confirmation message?

    Expecting quick response.
    Thanks in advance..

  47. dave said

    You have two choices really.
    1. Display the information to the user and allow them to make the choice
    2. If you have a list of servers you use you can add the key to the known_hosts file
    Something like this…
    localhost,127.0.0.1 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCuMx/rUpZrfU3R+cK+q1wmhgSFB/w3W6AK88yKPaNlpXNPA925MEQvNwimy86Ga6wg+9kxS41jgjKsyhU9CYtRW3hxq8HNRjyB4RUNDFC/l4k6R+gY1jQIEE1oaoltxsbHKOyZqPF0KDU4KrvZ0C0uwl0/G3I3/s4uww0W2TCqCQ==

    I went with option 2 because in my case this is server app that only communicates with a selection of known and trusted servers. If I remember correctly I found the key info using putty.
    Hope this helps
    Dave

  48. Ashok kumar said

    Hi Dave,

    Thanks for the reply. I will certainly consider the second option.
    After exploring the APIs, I found IgnoreHostKeyVerification class by which we can automatically approves the servers host key. I know it is insecure as well.

    Again, thanks for your quick reply.

    Thanks and Regards,
    Ashok kumar B.

  49. mahesh said

    Hi I am facing problem to download bigger files from windows machine to linux machine using sshtools.j2ssh API
    I am able to download smaller file, but for bigger files(more than 100mb) it didnot give any error but file not got download.
    I am able download any size of file from linux mchine to linux machine.
    Pleas help..Thanks in advance…

  50. Suji said

    hi
    i downloaded the j2ssh tool. i m using jdk1.5 the downloaded tool is in jdk’s lib folder.. when i execute any pgm using j2ssh i m getting import com.sshtools.j2ssh does not exist. i downloaded it frm source forge. i m not sure whether the import stnt is wrong..or something else..

  51. Vicky said

    Hi,
    I used j2SSH 0.2.7 to connect to a SSH server, but failed to create connection at sshClient.connect(”remote_host”, new IgnoreHostKeyVerification()) with following exceptions. Any idea?

    com.sshtools.j2ssh.transport.TransportProtocolException: The connection did not complete at com.sshtools.j2ssh.transport.TransportProtocolClient.onStartTransportProtocol(Unknown Source)
    at com.sshtools.j2ssh.transport.TransportProtocolCommon.startTransportProtocol(Unknown Source)
    at com.sshtools.j2ssh.SshClient.connect(Unknown Source)

  52. a2zjava said

    I am getting below exception , please advice if you know the reson.
    CODE
    =====
    ssh.connect(server,port, new IgnoreHostKeyVerification())

    ERROR
    =====
    INFO [Transport protocol 1] (com.sshtools.j2ssh.transport.TransportProtocolCommon) – Re
    ceived SSH_MSG_USERAUTH_FAILURE

  53. shab said

    I need help in executing multiple command in single session .
    it like logging into router in unprivileged mode than changing into privilege mode and then executing some command all in one session .

  54. mara said

    hola, tengo un problema, al usar el sftp, no está cerrando las conexiones del lado del server ¿que puedo hacer?

  55. alei said

    Thank you for the post.

  56. Greg S. said

    This was so helpful, Dave!
    Thank you so much!

  57. amardilo said

    This is really helpful thanks for posting this.

    Do you know if there is there a way to authenticate with a public and private key and can you set it to automatically accept host files and keys?

  58. The Professor said

    When I try this:
    SshClient ssh = new SshClient();

    My java class just dies. No exceptions, no messages, no fuss it just dies. Using jre 1.4.2_18

    What can I possibly look into?

  59. Chris said

    Has anybody got past the file size problem, if you transfer a file over 80kb it’s seems to crash the transfer sometimes.

  60. stefanus said

    Hi,
    I am using this sshtools sftp lib and I experience it keeps showing “waiting for new messages” inside the log files when I want to download file from SFTP Server. this error happens randomly so its difficult for me to find the caused. Is there any solution for this error ? or ways to avoid this kind of error

    Thank you

  61. Captain Rightworth said

    JSch does NOT DEPEND ON SWING/AWT. Only the examples they provide do.

  62. sunil said

    Does anyone have an example of configuring and running the SshDaemon server that is part of the sshtools library? I would like to run it on a port other than 22.

  63. gmale said

    As mentioned above, it seems J2SSH does not work with SSH1 keys. I’m getting all kinds of errors like:

    java.lang.NegativeArraySizeException

    and

    com.sshtools.j2ssh.transport.TransportProtocolException: The protocol version of the remote computer is not supported!

    Does anyone know of other libraries that don’t have this problem? I’m going to have to find a solution this week. If I find one, I’ll post back to this blog.

  64. Prasad said

    I am having some problem using j2ssh.I am getting below error.Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at com.sshtools.j2ssh.SshClient.(Unknown Source)
    MY Code:
    SshClient ssh = new SshClient();
    //HostKeyVerification host = new IgnoreHostKeyVerification();
    String hostname = “hostname”;
    String username = “username”;
    String password = “password”;
    ssh.connect(hostname);
    //ssh.connect(”firestar”, new ConsoleKnownHostsKeyVerification());
    PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
    pwd.setUsername(username);
    pwd.setPassword(password);
    int result = ssh.authenticate(pwd);

    Please suggest

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.