Spartan Java

Using SSH or SFTP resources from a Java app

by ricardoz on May.22, 2009, under Security

There are many commercial SSH client libraries for Java, but it was hard to find a good open source one. Finally I stumbled upon SSHTools and I have to say it works wonderfully and the API is clean and simple.

For example the following code snippet connects to a SFTP server and downlads a file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
SshClient ssh = new SshClient();
ssh.connect("someHost", 22);
 
// Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername("jhondoe");
passwordAuthenticationClient.setPassword("trustno1");
 
if (ssh.authenticate(passwordAuthenticationClient) != AuthenticationProtocolState.COMPLETE) {
   throw new IOException("Login failed");
}
 
//Open the SFTP client
SftpClient client = ssh.openSftpClient();
 
// We want to download the file to the local /tmp folder
client.lcd("/tmp");
 
// Download the file
client.get("/home/jhondoe/dummy.txt");
 
//disconnect
client.quit();
ssh.disconnect();

Bookmark it / share it:

  • Digg
  • del.icio.us
  • Google Bookmarks
  • Slashdot
  • Technorati
  • StumbleUpon
  • email
  • Facebook
  • LinkedIn
  • Print
  • NewsVine
  • Twitter
:, , , , , ,

2 Comments for this entry

  • The Professor

    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

    Any ideas on where to look for trouble?

  • ricardoz

    @The Professor:

    I would check that both the sshtools and the required JARs (packed with sshtools distribution) are in your classpath, and that an appropriate version of the JCE is available for you Java VM.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...