Copy a Directory using SCP and Java SSH

Introduction

SCP is very useful for the bulk transfer of directories across the network. In this example, we create a temporary local file structure, copy it over the remote server, and then copy it back.

SCP is not as powerful as SFTP and provides only file transfer functions. SFTP provides full file system access with the ability to get the file information, transfer files, create folders, delete files, and much more.

Source Code

package examples;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

import com.sshtools.client.SshClient;
import com.sshtools.client.scp.ScpClient;
import com.sshtools.common.files.direct.DirectFileFactory;
import com.sshtools.common.permissions.PermissionDeniedException;
import com.sshtools.common.ssh.ChannelOpenException;
import com.sshtools.common.ssh.SshException;
import com.sshtools.common.util.IOUtils;
import com.sshtools.common.util.Utils;

public class SCPDirectory {

public static void main(String[] args) throws IOException {

     try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
			
        String hostname = Utils.prompt(reader, "Hostname", "localhost");
        int port = 22;
        if (Utils.hasPort(hostname)) {
           port = Utils.getPort(hostname);
        }

        String username = Utils.prompt(reader, "Username", System.getProperty("user.name"));
        String password = Utils.prompt(reader, "Password");

        /**
         * SCP is very useful for the bulk transfer of directory across the network. In this
         * example we create a temporary local file structure and copy it to the remote
         * server, then copy it back.
         */
        try (SshClient ssh = new SshClient(hostname, port, username, password.toCharArray())) {

            ScpClient scp = new ScpClient(new DirectFileFactory(new File(".")), ssh);

            createFile("tmp_dir/1.dat", "10kb");
            createFile("tmp_dir/2.dat", "100kb");
            createFile("tmp_dir/3.dat", "1mb");
            createFile("tmp_dir/child/4.dat", "10kb");
            createFile("tmp_dir/child/5.dat", "16kb");
				
            scp.put("tmp_dir", ".", true, null, true);
		
            scp.get("tmp_return", "tmp_dir", true, null);
				
            ssh.disconnect();
         } catch (PermissionDeniedException | ChannelOpenException e) {
            e.printStackTrace();
         }

      } catch (IOException | SshException e) {
         e.printStackTrace();
      }
   }
	
   private static File createFile(String filename, String size) throws IOException {
      File file = new File(filename);
      file.getParentFile().mkdirs();
      file.createNewFile();
	
      RandomAccessFile localFile = new RandomAccessFile(file, "rw");
      localFile.setLength(IOUtils.fromByteSize(size));
      localFile.close();
      return file;
   }
}