Wednesday, December 05, 2007

SFTP using java api

Librery used SSHTools-J2SSH
Tutorial help from David Hayes

1
2 String userName = "someuser";

3 String password = "somepwd";
4
5 String host = "host_ip";

6 int port = 22;
7
8 String destinationPath = "<your_dest>";

9 String sourcePath = "<your_src>";
10
11 SshClient ssh = new SshClient();

12
13 try{
14 ssh.connect(host, port);

15
16 // Authenticate
17 PasswordAuthenticationClient passwordAuthenticationClient =
18 new PasswordAuthenticationClient();

19
20 passwordAuthenticationClient.setUsername(userName);
21 passwordAuthenticationClient.setPassword(password);

22
23 int result = ssh.authenticate(passwordAuthenticationClient);

24 if(result != AuthenticationProtocolState.COMPLETE){
25

26 throw new FTPException("Login to " + host + ":"

27 + port + " " + userName + "/" + password + " failed");

28
29 }
30
31 // Open the SFTP channel
32 SftpClient client = ssh.openSftpClient();

33 //change local directory where file would be copied
34 client.lcd(destination);
35 // download file

36 client.get(sourceFilePath);
37
38 client.quit();

39 ssh.disconnect();
40
41 }
42 catch(IOException e)

43 {
44
45 // file transfer failed
46 e.printStackTrace();

47 }




syntax highlighted by Code2HTML, v. 0.9.1

4 comments:

Anonymous said...

I'm trying to run this class, but I'm getting a noclassdeffound error, pointing to org/apache/commons/logging/LogFactory
And the stacktrace points to the SshClient-class.

Does the SshClient need the apache commons logging in the projects classpath or something?

Thanx

Sheetal said...

yeah, j2ssh library (including SshClient) uses commons logging and log4j api for logging.

Bill said...

I found this to be the most useful write-up of j2ssh SFTP. Thank you for posting!

(I should add that your pictures are beautiful!)

energizer bunny said...

NIce post, I also use this SFTP API called Zehon, it's great, so easy to use. Here is the site http://www.zehon.com