Skip to main content

File Transfer with scp

·396 words·2 mins
Yilin Fang
Author
Yilin Fang
PhD Student @ OSU CSE

scp (secure copy) is a command-line tool for copying files between machines over SSH. It uses the same authentication and encryption as ssh, so no extra setup is needed beyond SSH access.

Basic Syntax
#

The general syntax of scp is:

scp [options] source destination

Either source or destination (or both) can be remote. A remote path is written as:

user@host:/path/to/file

If user@ is omitted, the current local user is assumed.

Copy a local file to a remote machine
#

scp /path/to/local/file.txt user@remote_host:/path/to/remote/directory/

If the destination is a directory, the file is copied into it. If the destination file name does not exist, it will be created. If it exists, it is overwritten without warning.

Copy a file from a remote server to local
#

scp user@remote_host:/path/to/remote/file.txt /path/to/local/directory/

If the local target is a directory, the original file name is preserved.

Copy directories recursively
#

By default, scp only copies files. To copy directories, use the -r option:

scp -r results/ user@remote_host:/path/to/remote/directory/

Specify a different SSH port
#

If the remote SSH server listens on a non-standard port (not 22), use the -P (uppercase) option to specify the port:

scp -P 2222 /path/to/local/file.txt user@remote_host:/path/to/remote/directory/

This is different from ssh, which uses -p (lowercase) for specifying the port. Mixing them up is a common mistake.

Use an identity file (private key)
#

If you do not want to use the default SSH key, you can specify an identity file with the -i option:

scp -i /path/to/private_key.pem /path/to/local/file.txt user@remote_host
:/path/to/remote/directory/

This is useful when managing multiple servers with different keys.

Preserve file timestamps and modes
#

To preserve the original file timestamps and modes (permissions), use the -p option:

scp -p /path/to/local/file.txt user@remote_host:/path/to/remote/directory/

This matters when timestamps are important, e.g., for backup or synchronization.

Limit bandwidth usage
#

To avoid saturating the network, you can limit the bandwidth used by scp with the -l option (in Kbps):

scp -l 500 /path/to/local/file.txt user@remote_host:/path/to/remote/directory/

This can help when running transfers on a shared network.

Verbose output for debugging
#

If something fails or hangs, add -v (or -vv, -vvv) to see detailed SSH output:

scp -v /path/to/local/file.txt user@remote_host:/path/to/remote/directory/

This helps diagnose authentication, key and connection issues.

When not to use scp
#

For large directory trees or repeated synchronization, rsync is often better. It supports incremental transfer, resume, and better progress reporting. scp is most suitable for simple, direct copies.