How to Copy Folders to Remote Servers Using SSH

Copying folders between local and remote systems may not be a task you do daily, but sometimes you might need to do that. This guide will walk you through practical scenarios of using SSH to copy folders, focusing on the scp command. We'll cover basic usage, common issues, and tips to make your file transfers more efficient.

Copying a Project Folder

Scenario: You've been working on a project locally and need to upload it to your development server.

Steps:

  1. Open your terminal.
  2. Navigate to the parent directory of your project folder.
  3. Use the following command:
scp -r ./my_project user@dev_server:/home/user/projects/

Explanation:

  • -r: This flag enables recursive copying, essential for folders.
  • ./my_project: The local folder you're copying.
  • user@dev_server: Your username and the address of your dev server.
  • /home/user/projects/: The destination path on the server.

Downloading a Folder from Remote Server

Scenario: You need to download a large data folder from your company's remote server for local analysis.

Steps:

  1. Open your terminal.
  2. Navigate to where you want to download the folder.
  3. Use this command:
scp -r user@company_server:/path/to/data_folder ./

Tip: If it's a large folder, add the -C flag for compression:

scp -rC user@company_server:/path/to/data_folder ./

Copying Between Two Remote Servers

Scenario: You need to transfer a configuration folder from one server to another.

Steps:

  1. SSH into one of the servers.
  2. Use this command:
scp -r user1@server1:/path/to/config_folder user2@server2:/destination/path/

Note: This method uses your local machine as an intermediary. For large transfers, consider using rsync directly between servers if possible.

Dealing with Non-Standard SSH Ports

Scenario: Your server uses port 2222 for SSH instead of the default 22.

Solution: Use the -P flag to specify the port:

scp -P 2222 -r local_folder user@remote_server:/remote/path/

Preserving File Attributes

Scenario: You're migrating a website and need to keep all file permissions intact.

Solution: Use the -p flag to preserve modification times, access times, and modes:

scp -rp /local/website/files user@web_server:/var/www/html/

Conclusion

Mastering the scp command for copying folders via SSH is crucial for efficient file management across systems. By understanding these practical scenarios and tips, you'll be well-equipped to handle various file transfer tasks in your daily work. Remember to always verify your commands before execution, especially when dealing with important data.