ARTICLE - Cloud Servers

A Detailed Guide to Copying Files with scp on Linux

scp is a secure remote file copy command based on SSH that transfers files and directories between Linux servers with encryption. This article covers scp syntax, common parameters, and examples of uploading and downloading files and directories.

2023-04-03 cnblogs.com (CQZHUOMI)

A Detailed Guide to Copying Files with scp on Linux

scp is short for secure copy, a command used to copy files remotely on Linux. A similar command is cp, but cp only copies locally and cannot cross servers, while scp transfers are encrypted, which may slightly affect speed.

When the server disk becomes read-only, scp can help you move files out. In addition, scp is very light on resources and does not increase system load much. In this regard, rsync is far inferior: although rsync can be a bit faster than scp, when there are many small files rsync causes very high disk I/O, while scp basically does not affect normal system usage.

In day-to-day operations, scp is used most often for a few things: moving an entire site to a new machine during a server migration, pulling logs or backups from a production server back to your local machine for analysis, and distributing deployment packages between machines. It does not require any extra service to be running on the target — as long as SSH (port 22 by default) is open, it just works, which is exactly why operations teams prefer it over FTP.

1. Command Syntax

scp [options] [source] [destination]

2. Function

scp is the abbreviation of secure copy. It performs secure remote file copying based on SSH login and can copy files and directories between Linux servers.

3. Command Options

Option Description
-1 Force scp to use protocol ssh1
-2 Force scp to use protocol ssh2
-4 Force scp to use IPv4 addressing only
-6 Force scp to use IPv6 addressing only
-B Use batch mode (do not ask for transfer passwords or phrases during transfer)
-C Allow compression (passes the -C flag to ssh to enable compression)
-p Preserve modification time, access time, and access permissions of the original file
-q Do not display the transfer progress bar
-r Recursively copy the entire directory
-v Verbose output; scp and ssh show full debugging information for troubleshooting connection, authentication, and configuration issues
-c cipher Encrypt the data transfer with cipher, passed directly to ssh
-F ssh_config Specify an alternative ssh configuration file
-i identity_file Read the key file used for transfer from the specified file
-l limit Limit the bandwidth the user can use, in Kbit/s
-o ssh_option Use the parameter passing style of ssh_config
-P port Note the uppercase P; specifies the port used for data transfer
-S program Specify the program used for encrypted transfer; the program must understand ssh options

4. Usage Examples

Copy from the local server to a remote server:

Copy a file:

# With username (you will be prompted for the password), only the remote folder is given; the filename stays the same
scp local_file remote_username@remote_ip:remote_folder

# With username and a remote filename
scp local_file remote_username@remote_ip:remote_file

# Without username (you will be prompted for username and password), only the remote folder is given
scp local_file remote_ip:remote_folder

# Without username, with a remote filename
scp local_file remote_ip:remote_file

Copy a directory:

# With username
scp -r local_folder remote_username@remote_ip:remote_folder

# Without username
scp -r local_folder remote_ip:remote_folder

Copy from a remote server to the local server:

The command to copy from remote to local is similar, just swap the last two arguments of the local-to-remote command.

Example 1: Copy a file from remote to a local directory

scp [email protected]:/opt/soft/nginx-0.5.38.tar.gz /opt/soft/

Explanation: download the nginx-0.5.38.tar.gz file from /opt/soft/ on machine 192.168.120.204 to the local /opt/soft/ directory.

Example 2: Copy a directory from remote to local

scp -r [email protected]:/opt/soft/mongodb /opt/soft/

Explanation: download the mongodb directory from machine 192.168.120.204 to the local /opt/soft/ directory.

Example 3: Upload a local file to a remote directory

scp /opt/soft/nginx-0.5.38.tar.gz [email protected]:/opt/soft/scptest

Explanation: copy the nginx-0.5.38.tar.gz file in the local /opt/soft/ directory to the /opt/soft/scptest directory on remote machine 192.168.120.204.

Example 4: Upload a local directory to a remote directory

scp -r /opt/soft/mongodb [email protected]:/opt/soft/scptest

Explanation: upload the local directory /opt/soft/mongodb to the /opt/soft/scptest directory on remote machine 192.168.120.204.

Example 5: Copy multiple files at once, with a custom port and compression

scp -P 2222 -C file1.txt file2.txt [email protected]:/opt/soft/

Explanation: copy the local files file1.txt and file2.txt to the remote directory in one go over port 2222 with compression enabled. -P sets the port and -C enables compression; both can be freely combined with other options.

5. scp vs rsync: Which to Choose

scp is good enough for many cases, but rsync is usually a better fit for large files and repeated transfers. The trade-offs can be seen from a few dimensions:

Dimension scp rsync
Resume interrupted transfers No Yes
Incremental transfer No (full copy) Yes (only differences)
System load Low High I/O with many small files
Target machine requirement SSH only rsync usually needs to be installed
Permission preservation -p preserves time/perms Preserved by default, finer options

In short: use scp for one-off copies or when rsync cannot be installed on the target; use rsync when you need periodic syncs with large, changing file sets.

6. Common Errors and Troubleshooting

Error Cause Fix
Permission denied (publickey,password) Wrong username/password or key Verify username and key path; check ~/.ssh/authorized_keys on the target
Connection refused SSH not listening on that port Confirm sshd is running and the -P port matches the target
Host key verification failed Target host key changed Verify the host fingerprint, then remove the stale entry from ~/.ssh/known_hosts
scp: command not found Missing openssh-clients Install openssh-clients (CentOS) or openssh-client (Ubuntu)
Transfer very slow High latency or no compression Add -C for large text files, or throttle to avoid affecting production

When transferring large files, throttle with -l, for example -l 10000 limits to 10,000 Kbit/s (about 1.2MB/s), so scp does not saturate the bandwidth and impact other services.

Summary

  • Copying files does not need -r; copying directories always requires -r;
  • Use uppercase -P to specify the port;
  • For scenarios with many small files, scp has less impact on system I/O and is preferred.

If you get scp: command not found, the local or target machine lacks openssh-clients; see installing the scp command on CentOS. For more Linux file operations and server operations content, see the cloud servers category, such as Linux server basics.

Reference: OpenSSH scp man page https://man.openbsd.org/scp; rsync documentation https://rsync.samba.org/documentation.html

Original post: https://www.cnblogs.com/cqzhuomi/articles/17284311.html (cnblogs.com CQZHUOMI, repost)

Integration & Code Examples

Example 1: Common scp forms and their limits

# explicit port plus recursive directory upload
scp -P 2222 -r ./dist/ [email protected]:/var/www/app/dist/

# compress on the fly and cap throughput (Kbit/s) so uploads do not saturate
scp -C -l 8000 backup.tar.zst [email protected]:/data/

# a specific key, and only that key: stop the agent from trying every other one
scp -i ~/.ssh/deploy_ed25519 -o IdentitiesOnly=yes report.csv [email protected]:/tmp/

# pull a directory back for reconciliation or debugging
scp -P 2222 -r [email protected]:/var/log/app/ ./logs/

Note that -P (uppercase) is the port while -p (lowercase) preserves timestamps and modes; the two are often confused.

Example 2: Resumable and incremental transfers belong to rsync

# --partial keeps the half-written file so a rerun continues; -z compresses; -e passes ssh flags
rsync -avz --partial --progress -e 'ssh -p 2222' \
  ./dist/ [email protected]:/var/www/app/dist/

# dry-run first to see what --delete would remove
rsync -avz --delete --dry-run site/ [email protected]:/var/www/site/

# afterwards compare by checksum to prove both ends match
rsync -avzc --dry-run ./dist/ [email protected]:/var/www/app/dist/

# avoid business hours by capping throughput (KB/s)
rsync -avz --bwlimit=2000 ./dist/ [email protected]:/var/www/app/dist/

scp restarts a file from byte zero, so a dropped connection on a few hundred MB costs the whole transfer; day-to-day deploys are cheaper with rsync's delta algorithm, and --dry-run prevents accidental deletions.

Six Flags Worth Knowing, and What Mixing Them Up Costs

Only six groups of scp flags come up daily: -r for directories, -P for the port, -p for timestamps and permissions, -l for bandwidth, -C for compression, and -i with -o IdentitiesOnly=yes for key selection. The rest cover protocol version, address family and debug output and rarely change.

The pair most often confused is -P and -p: uppercase is the port, lowercase preserves attributes. The cost is asymmetric — a wrong port fails immediately, while a wrong attribute flag quietly drops permissions until someone tries to execute the file after a deploy.

Flag Purpose Typical combination What goes wrong
-r Copy directories recursively scp -P 2222 -r ./dist/ [email protected]:/var/www/ Only the directory entry is sent, with a cannot-copy-directory message
-P port SSH port (uppercase) scp -P 2222 file user@host:/tmp/ Connects to port 22 and reports Connection refused
-p Keep mtime, atime and permissions scp -p app.conf user@host:/etc/app/ Permissions fall back to defaults and the execute bit is lost
-l limit Bandwidth limit in Kbit/s scp -l 10000 backup.tar user@host:/data/ Upload saturates and affects production traffic
-C Compress during transfer scp -C file1.txt file2.txt user@host:/opt/ Large text files take longer
-i with -o IdentitiesOnly=yes Use one specific key only scp -i ~/.ssh/deploy_ed25519 -o IdentitiesOnly=yes report.csv user@host:/tmp/ Every agent key is tried, ending in rejection or timeout

Deciding Between scp and rsync for Large Files and Weak Links

A one-off copy and a repeated sync are different transfer shapes. scp always starts from zero, so a few hundred megabytes must restart after a drop; rsync keeps a partial file with --partial and resumes, and sends only the differences.

Bandwidth limits use different units: scp's -l 10000 means 10000 Kbit/s (about 1.2MB/s), while rsync's --bwlimit=2000 is in KB/s. Converting for the same target rate matters — copying the number across changes the limit by a factor of eight.

Direction changes the risk too. A sync with --delete removes extra files on the destination, so inspect the list with --dry-run first; after transfer, compare the two sides by checksum with rsync -c, which is stricter than comparing file sizes. When the destination cannot install rsync, stay with scp and use -C plus -l to bound resource use.

Limitations

  • In addition, scp is very light on resources and does not increase system load much.
  • Figures reflect public information at publication; terms, prices and quotas follow the provider's current published terms.
  • This article reflects public information as of 2023-04-03; terms, prices and quotas follow the provider's current published terms.

FAQ

Which should I use for large log files, scp or rsync?

Use rsync. It resumes after an interruption and sends only the changed bytes, while scp restarts the whole transfer every time, so a few hundred MB gets painful. Keep scp for small deploy bundles when the target host cannot install rsync: it needs nothing beyond SSH on port 22.

Does the -l bandwidth limit add any cost?

Kilobits per second. -l 10000 caps the transfer at 10000 Kbit/s, roughly 1.2MB/s, and the value carries no suffix, so every number is read as Kbit/s. The flag costs nothing extra, but you are spending the target host's outbound bandwidth, so start at half your monitoring threshold and tune after a load test.

Which prerequisites must exist before the first copy?

Only an SSH server, on port 22 by default. The local host needs the scp binary, which ships with openssh-client or openssh-clients; if it reports command not found, install the package for your distribution. Key login also requires the public key in ~/.ssh/authorized_keys on the target.

Related Providers

  • Hetzner: use it when the target is a European hourly-billed cloud host receiving scheduled scp log syncs.
  • Tencent Cloud: use it when the target is a mainland CVM reached over an in-region private address.
  • Alibaba Cloud ECS: use it when both instances sit in one Alibaba Cloud VPC and copy by private IP.

Community & Resources

Official docs and communities

  • scp(1) — option list and the -P vs -p distinction
  • rsync(1) — delta algorithm, --partial and filter rules
  • sshd_config(5) — server-side ports, auth and chroot
  • sftp(1) — interactive transfers and batch mode

Learning resources and tools

Original source: cnblogs.com (CQZHUOMI) ↗