Secure Copy (SCP) is a protocol used for securely transferring files over a network using Secure Shell (SSH). It allows you to copy files between a local machine and a remote server, or between two remote servers. In this tutorial, we will explore how to use SCP to transfer files in both directions.
Basic Syntax
The basic syntax of the SCP command is:
scp [options] source destination
Where source
and destination
can be either local files or remote files specified in the format user@host:file
.
Downloading Files from a Remote Server
To download a file from a remote server, you would use the following command:
scp user@remote_host:remote_file local_file
Replace user
with your username on the remote server, remote_host
with the hostname or IP address of the remote server, remote_file
with the path to the file you want to download, and local_file
with the path where you want to save the file.
For example:
scp [email protected]:/home/johndoe/example.txt ~/Downloads/
This command will download the example.txt
file from the remote server and save it in the ~/Downloads/
directory on your local machine.
Uploading Files to a Remote Server
To upload a file to a remote server, you would use the following command:
scp local_file user@remote_host:remote_file
Replace local_file
with the path to the file you want to upload, and user
, remote_host
, and remote_file
with the same values as before.
For example:
scp ~/Documents/example.txt [email protected]:/home/johndoe/
This command will upload the example.txt
file from your local machine to the remote server and save it in the /home/johndoe/
directory.
Copying Directories
To copy directories, you need to use the -r
option, which stands for recursive. The syntax is:
scp -r source destination
For example, to download a directory from a remote server:
scp -r user@remote_host:remote_directory local_directory
And to upload a directory to a remote server:
scp -r local_directory user@remote_host:remote_directory
Note that if you want to preserve the permissions, timestamps, and other attributes of the files, you can use the -p
option in addition to -r
.
Tips and Variations
- If the usernames on the local and remote hosts are the same, you can omit the username when specifying a remote file.
- You can use the
~
symbol to refer to your home directory on the remote server. - You can use the
.
symbol to refer to the current working directory on the remote server. - You can use SCP with other SSH options, such as
-c
to specify a cipher or-i
to specify an identity file.
By following these examples and tips, you should be able to use SCP to transfer files securely over SSH. Remember to always use the correct syntax and options for your specific use case.