15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
28.10.2024
2 +1

Copying Files via SSH: Complete Guide to SCP, rsync, and SFTP

SSH (Secure Shell) is the backbone of secure remote server management. Whether you're a developer deploying code, a sysadmin managing infrastructure, or a power user maintaining a VPS Hosting environment, transferring files securely between machines is a task you'll perform constantly.

This comprehensive guide covers every major method for copying files via SSH — including SCP, rsync, SFTP, and key-based automation — with real-world syntax, practical examples, and expert tips to help you work faster and more securely.

Why Use SSH for File Transfers?

Before diving into the tools, it's worth understanding why SSH-based file transfer is the industry standard for server administrators and developers alike.

  • End-to-end encryption: Every byte of data — including credentials, commands, and file contents — is encrypted in transit using modern cryptographic algorithms. This makes SSH transfers immune to packet sniffing and man-in-the-middle attacks.
  • No additional software required: SSH is pre-installed on virtually every Linux/Unix system and is natively available on Windows 10+ and macOS.
  • Versatility: A single SSH connection can handle interactive shell sessions, file transfers, port forwarding, and automated scripting.
  • Automation-friendly: SSH integrates seamlessly with cron jobs, CI/CD pipelines, and backup scripts, enabling fully automated, passwordless file transfers.
  • Reliability: SSH connections handle network interruptions gracefully, especially when combined with tools like rsync.

Method 1: Copying Files with SCP (Secure Copy Protocol)

SCP is the simplest and most widely used tool for one-time file transfers over SSH. It works by leveraging your existing SSH connection to securely copy files between hosts.

Basic SCP Syntax

scp [options] [source] [destination]

Example 1: Upload a File from Local Machine to Remote Server

scp /path/to/local/file username@remote_host:/path/to/remote/destination

Breakdown:

    /path/to/local/file — the file you want to transfer on your local machine
    username@remote_host — your SSH username and the server's hostname or IP address
    /path/to/remote/destination — the target directory or file path on the remote server
    
    Example 2: Download a File from Remote Server to Local Machine
    scp username@remote_host:/path/to/remote/file /path/to/local/destination
    Simply reverse the source and destination to pull a file from the server to your local machine.
    Example 3: Copy an Entire Directory Recursively
    scp -r /path/to/local/directory username@remote_host:/path/to/remote/destination
    The -r flag tells SCP to copy the directory and all of its contents recursively, including nested subdirectories.
    Useful SCP Options
    
    
    
    
    Option
    Description
    
    
    
    
    -P [port]
    Specify a custom SSH port (note: uppercase -P, unlike SSH's lowercase -p)
    
    
    -C
    Enable compression for faster transfers over slow connections
    
    
    -i [identity_file]
    Use a specific SSH private key for authentication
    
    
    -l [limit]
    Limit bandwidth usage in Kbit/s
    
    
    -q
    Quiet mode — suppress progress output
    
    
    -v
    Verbose mode — useful for debugging connection issues
    
    
    
    
    When to Use SCP
    SCP is ideal for quick, one-time file transfers where simplicity matters. It requires no configuration and works out of the box on any system with SSH installed. However, for large directories or repeated transfers, rsync is a significantly better choice.
    Method 2: Copying Files with rsync
    rsync is the professional's choice for file synchronization and transfer over SSH. Its killer feature is delta transfer: instead of copying entire files, rsync analyzes the source and destination and transfers only the changed portions. This saves enormous amounts of time and bandwidth when dealing with large files or directories that are updated frequently.
    Basic rsync Syntax
    rsync [options] [source] [destination]
    Example 1: Upload a File from Local Machine to Remote Server
    rsync -avz /path/to/local/file username@remote_host:/path/to/remote/destination
    Example 2: Sync an Entire Directory to a Remote Server
    rsync -avz /path/to/local/directory/ username@remote_host:/path/to/remote/destination/
    > Important: Note the trailing slash / after the source directory. With a trailing slash, rsync copies the *contents* of the directory. Without it, rsync copies the directory itself as a subdirectory of the destination.
    Example 3: Mirror a Directory (Delete Files Removed from Source)
    rsync -avz --delete /path/to/local/directory/ username@remote_host:/path/to/remote/destination/
    The --delete flag ensures that files deleted from the source are also removed from the destination, keeping both locations perfectly in sync.
    Example 4: Use a Custom SSH Port
    rsync -avz -e "ssh -p 2222" /path/to/local/directory/ username@remote_host:/path/to/remote/destination/
    Useful rsync Options
    
    
    
    
    Option
    Description
    
    
    
    
    -a
    Archive mode: preserves permissions, timestamps, symbolic links, and ownership
    
    
    -v
    Verbose: displays file-by-file progress during transfer
    
    
    -z
    Compression: reduces data transferred over the network
    
    
    --delete
    Deletes files at the destination that no longer exist at the source
    
    
    --progress
    Shows real-time progress for each file
    
    
    --exclude
    Exclude specific files or patterns (e.g., --exclude '*.log')
    
    
    -n or --dry-run
    Simulate the transfer without actually copying anything
    
    
    -e "ssh -p [port]"
    Specify a custom SSH port
    
    
    --bwlimit=[KB/s]
    Throttle transfer speed to avoid saturating your connection
    
    
    
    
    When to Use rsync
    Use rsync for backups, deployments, and any recurring synchronization task. It's especially powerful when managing large codebases, media libraries, or database exports on a Dedicated Server where bandwidth efficiency and data integrity are critical.
    Method 3: Copying Files Between Two Remote Servers
    A less commonly known but extremely useful capability of both SCP and rsync is the ability to transfer files directly between two remote servers — without routing the data through your local machine. This is invaluable when migrating servers or syncing data between cloud instances.
    Copy Files Between Two Remote Servers with SCP
    scp username1@remote_host1:/path/to/file username2@remote_host2:/path/to/destination
    Copy Files Between Two Remote Servers with rsync
    rsync -avz username1@remote_host1:/path/to/source/ username2@remote_host2:/path/to/destination/
    > Note: For server-to-server transfers to work, the source server must be able to establish an SSH connection to the destination server. You may need to configure SSH keys on the source server or use SSH agent forwarding (ssh -A).
    Server-to-Server Transfer via SSH Tunneling (Alternative Method)
    If direct server-to-server SSH isn't possible due to firewall restrictions, you can pipe the transfer through your local machine using tar and ssh:
    ssh username1@remote_host1 "tar czf - /path/to/source" | ssh username2@remote_host2 "tar xzf - -C /path/to/destination"
    This streams a compressed archive from server 1 directly into server 2 via your local terminal session.
    Method 4: Copying Files with SFTP (SSH File Transfer Protocol)
    SFTP provides an interactive, FTP-like experience over an encrypted SSH connection. Unlike SCP, which is a single-command tool, SFTP opens a persistent session where you can browse directories, upload, download, rename, and delete files interactively.
    Starting an SFTP Session
    sftp username@remote_host
    You'll be dropped into an SFTP prompt (sftp>), from which you can run the following commands:
    Essential SFTP Commands
    
    
    
    
    Command
    Description
    
    
    
    
    ls
    List files in the current remote directory
    
    
    lls
    List files in the current local directory
    
    
    cd /remote/path
    Change the remote directory
    
    
    lcd /local/path
    Change the local directory
    
    
    put /local/file /remote/destination
    Upload a file to the remote server
    
    
    get /remote/file /local/destination
    Download a file from the remote server
    
    
    mput *.txt
    Upload multiple files matching a pattern
    
    
    mget *.log
    Download multiple files matching a pattern
    
    
    mkdir /remote/newdir
    Create a directory on the remote server
    
    
    rm /remote/file
    Delete a file on the remote server
    
    
    exit or quit
    Close the SFTP session
    
    
    
    
    Connecting to a Custom SSH Port via SFTP
    sftp -P 2222 username@remote_host
    When to Use SFTP
    SFTP is best suited for interactive file management sessions — for example, when you need to browse a remote directory structure, selectively download log files, or upload configuration files to a web server. Many GUI clients (such as FileZilla, Cyberduck, and WinSCP) use SFTP as their underlying protocol, making it accessible to non-technical users as well.
    Method 5: Automating File Transfers with SSH Key Authentication
    Manually entering a password for every file transfer is inefficient and incompatible with automation. SSH key-based authentication solves this by allowing passwordless, cryptographically secure logins — a prerequisite for any automated backup or deployment workflow.
    Step 1: Generate an SSH Key Pair
    On your local machine, run:
    ssh-keygen -t ed25519 -C "your_email@example.com"
    > Note: ed25519 is the modern, recommended algorithm. Use -t rsa -b 4096 if you need compatibility with older systems.
    Follow the prompts to save the key (default location: ~/.ssh/id_ed25519) and optionally set a passphrase for added security.
    Step 2: Copy Your Public Key to the Remote Server
    ssh-copy-id username@remote_host
    This appends your public key to the ~/.ssh/authorized_keys file on the remote server. You'll be prompted for your password one final time.
    If ssh-copy-id isn't available, you can do this manually:
    cat ~/.ssh/id_ed25519.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
    Step 3: Test Passwordless Authentication
    ssh username@remote_host
    If you connect without being prompted for a password, key-based authentication is working correctly.
    Step 4: Automate Transfers with a Shell Script
    With passwordless SSH configured, you can now automate file transfers in cron jobs or scripts:
    #!/bin/bash
    # Daily backup script
    rsync -avz --delete /var/www/html/ username@backup_server:/backups/www/
    Add this to your crontab (crontab -e) to run nightly:
    0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
    Troubleshooting Common SSH File Transfer Issues
    Even experienced administrators run into issues. Here are the most common problems and their solutions:
    Permission Denied (publickey)
    
    Verify the public key is correctly added to ~/.ssh/authorized_keys on the remote server
    Check that ~/.ssh has permissions 700 and authorized_keys has permissions 600
  • Confirm the SSH daemon allows key authentication (PubkeyAuthentication yes in /etc/ssh/sshd_config)
  • Connection Refused

    • Verify the SSH service is running: systemctl status sshd
    • Check that the correct port is being used
    • Review firewall rules: ufw status or iptables -L

    Transfer Speed Is Slow

    • Enable compression: add -C to SCP or -z to rsync
    • Use a faster cipher: ssh -c aes128-ctr (less secure but faster on high-latency links)
    • For large transfers, consider rsync with --bwlimit to avoid saturating your network

    Host Key Verification Failed

    • The remote server's SSH fingerprint has changed (could indicate a security issue or a server rebuild)
    • Remove the old key: ssh-keygen -R remote_host
    • Reconnect and verify the new fingerprint before accepting it

    Choosing the Right Tool: SCP vs. rsync vs. SFTP

    FeatureSCPrsyncSFTP
    Ease of use⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
    Delta transfers
    Directory sync✅ (recursive)✅ (with --delete)✅ (manual)
    Interactive mode
    Automation✅ (with scripts)
    Bandwidth efficiencyLowHighLow
    Best forQuick one-time transfersBackups & syncInteractive browsing

    Securing Your SSH File Transfers: Best Practices

    Regardless of which tool you use, follow these security best practices to protect your servers and data:

    1. Disable password authentication — Use SSH keys exclusively and set PasswordAuthentication no in /etc/ssh/sshd_config
    2. Change the default SSH port — Moving away from port 22 dramatically reduces automated brute-force attempts
    3. Use fail2ban — Automatically ban IPs that repeatedly fail authentication
    4. Restrict SSH access by IP — Use firewall rules or AllowUsers directives to limit who can connect
    5. Keep SSH updated — Regularly update OpenSSH to patch known vulnerabilities
    6. Use strong key algorithms — Prefer ed25519 or rsa-4096 over older, weaker algorithms
    7. Secure your web applications — Pair SSH security with an SSL Certificate to encrypt all traffic to your web services

    Frequently Asked Questions

    What is the difference between SCP and SFTP?

    SCP is a non-interactive command-line tool designed for fast, single-command file transfers. SFTP is an interactive protocol that allows you to browse, manage, upload, and download files in a session-based interface. Both use SSH for encryption.

    Can I use rsync without SSH?

    Yes — rsync has its own daemon mode that operates without SSH, but it's less secure. For any internet-facing transfer, always use rsync over SSH (rsync -e ssh).

    How do I transfer files if my server uses a non-standard SSH port?

    Use the -P flag with SCP (scp -P 2222) or the -e "ssh -p 2222" option with rsync. For SFTP, use sftp -P 2222.

    Is SCP deprecated?

    OpenSSH developers have noted that SCP's underlying protocol has limitations and recommend using SFTP or rsync for new workflows. However, SCP remains widely available and functional on virtually all systems.

    Conclusion

    Mastering SSH-based file transfer is an essential skill for anyone managing servers, deploying applications, or maintaining remote infrastructure. Each tool has its place:

    • SCP is your go-to for fast, simple, one-off transfers
    • rsync is indispensable for backups, deployments, and efficient synchronization of large data sets
    • SFTP excels in interactive sessions where you need to browse and manage files on the fly

    Combining these tools with SSH key authentication and solid security practices gives you a robust, automated, and secure file transfer workflow that scales from a single Shared Web Hosting account all the way up to complex multi-server architectures on Dedicated Servers.

    If you're looking for a reliable, high-performance hosting environment to put these skills into practice, explore AlexHost's VPS Hosting plans — built for developers and sysadmins who demand full root access, SSD storage, and enterprise-grade network connectivity.

    15%

    Save 15% on All Hosting Services

    Test your skills and get Discount on any hosting plan

    Use code:

    Skills
    Get Started