How To Copy Files over SSH with SCP

Introduction
SCP (secure copy) is a command line utility that allows you to securely copy files and directories between two servers.
With “scp” you can copy a file or directory:
- From your local system to a remote system.
- From a remote system to your local system.
- Between two remote systems from your local system.
Note: When transferring data with “scp”, both the files and password are encrypted.
SCP Command Syntax
The scp
command syntax has the following syntax structure:
scp [OPTIONS] [[user@]src_host:]file [[user@]dest_host:]file
The most common options:
-p Preserves modification times, access times, and modes from the original file.
-P port Specifies the port to connect to on the remote host.
-r Recursively copy entire directories. Note that scp follows symbolic links encountered in the tree traversal.
-q Quiet mode: disables the progress meter as well as warning and diagnostic messages.
-C Compression enable. Passes the -C flag to ssh(1) to enable compression.
Note: Local files should be specified using an absolute or relative path, while remote file names should include a user and the host specification.
Example of scp from local to remote
In the following example we are doing a Secure Copy of a directory from the local host to a remote server :
lag@core:~$ scp -r /local/directory/ user@host:/remote/directory/
Note: In this example the option -r allows you to copy recursively entire directories. You will be prompted for the user’s password.
Example of scp from remote to local
We are doing now a secure copy of a remote file to the local machine:
scp user@src_host:/remotedir/file.txt /local/directory/
Note: You will be prompted for the user’s password.
Example of scp from remote to remote
We are doing now a secure copy of a remote directory to a remote machine:
scp -r user@src_host:/remotedir/mydir user@dest_host:/remotedir/mydir
Note: You will be prompted for both users passwords.
Tips for using SCP
The scp command relies on ssh for data transfer, so it requires a SSH KEYS or the password to authenticate on the remote systems.
The colon “:” is how scp distinguish between local and remote locations.
To be able to copy files, you must have at least read permissions on the source file and write permission on the target system.
Be careful when copying files that share the same name and location on both systems, scp will overwrite files without warning.
When transferring large files, it’s recommended to run the scp command inside a screen or tmux session so it does not get interrupted.
Conclusion
As we learn from this tutorial, we can use SCP to copy files or directories from or to remote machines in a fast and secure way, just like you would do in your local server.
If you to want learn more about this tutorial or have any questions, please feel free to send your comments in the form down below.
Tags: Copy Files SSH, SCP, Secure Copy