Transferring Files

In Creating an SSH Client, we demonstrated how to connect to an SSH server and authenticate the user. SFTP is a file transfer protocol that runs over the SSH connection and is now one of the most widely used secure file transfer mechanisms.

The SshClient provides a high-level API to perform basic file transfers. If you have a more complex requirement, want to manage file permissions or perform more advanced operations, you should look at our SftpClientTask, documented in Implementing an SFTP Client.

Uploading Files

In its simplest form, we can just pass a File object to the putFile method to transfer this to the remote server.

In the example below, a file called maverick.zip will be placed in the users’ default directory, typically their home directory. 

try (SshClient ssh = SshClientBuilder.create()
		.withHostname("localhost")
		.withPort(2222)
		.withUsername("root")
		.withPassword("xxxx")
		.build()) {
    ssh.putFile(new File("/Users/lee/Downloads/maverick.zip")); 
}

We can pass the remote path if we want to control where the file is placed on the server. For example, this places the file in the /tmp folder:

ssh.putFile(new File("/Users/lee/Downloads/maverick.zip"). "/tmp"); 

We can also optionally set a timeout limit. Note that this is not a socket timeout but a time limit on the operation. An exception will be raised if the operation fails to complete within the time limit provided.

ssh.putFile(new File("/Users/lee/Downloads/maverick.zip"). "/tmp", 60000L); 
Downloading Files

Similarly, we can download files with the getFile method. Passing the file’s path on the remote server, the file will be downloaded to the same name in the user’s home directory.

File dest = ssh.getFile("maverick.zip");

We can control where the file is placed by passing our file instance.

File dest = new File("/tmp");
ssh.getFile("maverick.zip", dest);

As with all high-level operations, we can provide a timeout value.

ssh.getFile("maverick.zip", dest, 60000L);