How to Use the SCP Command to Securely Transfer Files

How to Use SCP Command to Securely Transfer Files + Examples

SCP (Secure Copy) is a command-line based utility for securely transferring files between a local and a remote system, or between two remote systems.

With scp you can copy files or directories in the following ways:

  1. From your local system to a remote system
  2. From a remote system to your local system
  3. Between two remote systems, while sending the commands from your local system.

About the SCP Command

SCP is usually used to refer to both SCP (the command-line utility, developed by the OpenSSH Project), as well as Secure Copy Protocol, which is the protocol used by the utility.

SCP is based on the Secure Shell (SSH) protocol, and it comes with a similar set of options, and is provided in most SSH implementations.

It uses credentials (such as passwords or SSH keys) for authentication, and it secures your transfers by encrypting both passwords and the transferred data, so your contents should be impervious to snooping.

A related protocol is SFTP (Secure File Transfer Protocol), however SCP does not have some of the capabilities that SFTP does, such as resuming broken transfers or remote file manipulation, like deletion.

Before You Begin

Requirements

  1. To be able to transfer files from/to remote hosts via scp, you need the user’s authentication credentials – such as user/password or SSH keys.
  2. To be able to transfer files between systems you must have at least read permissions on the source file and write permissions on the destination system.

Useful Info

By default, scp operates on port 22 unless you change it using a command-line option.

You can use SCP with Linux, Mac, and Windows.
SCP should already be installed on Linux and Mac, however on Windows you have to install it – if you’re on Windows please see the section below on installing SCP on Windows.

When transferring large files, you’ll probably have to wait some time for the transfers to finish. For various reasons, you may not want to have to keep the command line open for hours. A solution here is running scp inside a terminal multiplexer such as screen or tmux, which allow you to leave commands running even if you log off.

SCP Command Syntax

The basic syntax of SCP is the following.

scp [OPTIONS] [[[email protected]]SOURCE_HOST:]file1 [[[email protected]]DESTINATION_HOST:]file2

Let’s break down and explain what the above expression means:

[OPTIONS]: Options alter scp’s behavior, such as changing the encryption cipher, ssh_config location, identity file location, limit bandwidth, change SSH port, recursive copy, and others.

You can check all available options by running man scp in the command line or read the scp man page online.

[[[email protected]]SOURCE_HOST:]file1: This is the source file, the file to be copied.

If you’re copying from your local machine then you should just specify the relative (~/file1) or absolute path (/home/edxd/file1).

If the source file is located on a remote system, then you’ll have to specify the user and host ([email protected]_source_ip) followed by the colon (:) separator, and then the file’s absolute or relative path.

For example: [email protected]:/var/www/file1.txt

[[[email protected]]DESTINATION_HOST:]file2: This is the destination file, where the file is going to be copied.

If you’re copying to a remote host, it should include the user and host specification [email protected]_destination_ip:/path/to/file2.

If you’re copying from a remote host to your machine, absolute or relative path where you want the file copied, such as just /path/to/file2.

There are a few ways you can handle the remote user and host specifications.

You can use:

  1. an IP address: [email protected]
  2. a domain name: [email protected]
  3. a host defined in the /etc/hosts file
  4. a host defined in ~/.ssh/config (or %userprofile%\.ssh\config on Windows, usually C:\Users\your_user\.ssh\config)

Copy Files and Directories Between Two Hosts With SCP

1. Copy a Local File to a Remote Host Using SCP Command

It’s one of the most straightforward SCP commands you can carry out. We’re copying a single file (example.txt) from our computer to our remote host, which has .

To copy a local file to a remote host run a command like:

scp /path/to/example.txt [email protected]:/remote/path

Let’s quickly explain the above command.

/path/to/example.txt is the path to the file you want to copy from your local computer, remote_user is the user on the remote server, 121.134.21.14 is the IP of the remote host.

Next, comes a colon : after which you can specify the path where you want the file to be copied (/remote/path/). The copied file will retain it’s original name.

Here is a video to illustrate how this works. I’ll run the following command:

scp example.txt [email protected]:/home/stelixd

In the video below, on the left, we have a terminal on our local computer, and on the right we have the terminal of an Ubuntu remote server.

1. SCP Command - Copy a file from your local computer to a remote host

If you are connecting to your remote host for the first time, you will see the prompt Are you sure you want to continue connecting (Yes/no)?.

Assuming you trust the remote server, type Yes, press Enter, and fill in the user password (if you’re not using SSH keys).

When we execute the ls command on the server, you can see the example.txt was successfully copied.

You can also specify a new name for the file (/remote/path/file1_new_name):

scp /path/to/file1 [email protected]:/remote/path/file1_new_name

Copy Multiple Local Files to a Remote Host

You can also copy multiple local files on our remote host in a single command. In my case I’ll transfer movie1.mp4, movie2.mp4, movie3.mp4, and movie4.mp4.

To transfer multiple local files with scp just include all of them in the command, separated by a space:

scp movie1.mp4 movie2.mp4 movie3.mp4 movie4.mp4 [email protected]:/home/stelixd

2. Copy a Remote File to Your Local Machine Using SCP Command

To copy a remote file to your local machine, just use the remote location as the source file, and the local location as the destination:

scp [email protected]:/home/stelixd/example.txt example.txt

Copy Multiple Remote Files to Your Local Machine

To copy multiple remote files to our local machine, use the following syntax:

scp [email protected]_destination:/some/remote/directory/\{file1,file2,file 3\} /some/local/directory

Where [email protected]_destination is your remote host details, /some/remote/directory/ is a directory on your remote host, and \{file1,file2,file3\} are the files we want to transfer, separated by a comma, in escaped (\) curly braces {}.

Escaping is a method that allows us to tell a computer to do something special with the text we supply or to ignore the special function of a character. To tell the computer that it should expect an escape character we use a special escape marker, we usually make use of the backslash \, such as we have done with the curly braces (\{, \}).

Here is an example of me transferring 3 empty files from a remote server to a local computer:

scp mrtest:/home/edxd/\{file1,file2,file3\} /home/stelixd/
Output
file1 100% 5120KB 2.5MB/s 00:01
file2 100% 11MB 8.1MB/s 00:01
file3 100% 8192KB 8.0MB/s 00:00

3. Copy a File between Two Remote Hosts Using the SCP Command

With scp you can copy files from a remote host directly to another remote host, all without having to SSH into any of them.

You’ll just send the command from a third machine, such as your local computer. The following command will copy file1 between two remote machines:

scp [email protected]_host_1:/var/www/file1 [email protected]_host_2:/var/www/file2

Video Demo
Here is an example where I copy a file between two remote hosts with scp:

scp [email protected]:/home/edxd/my_file [email protected]:/home/stelixd
5. SCP Command - Copy Files Across Remote Hosts

Important: In some cases scp hangs, and doesn’t prompt you for both passwords so it can proceed with the transfer, and I’m not yet sure the reason for this.

One solution for this is setting up SSH-key based authentication between the computer issuing the command, and both the remote hosts.

Copy Files Between Two Remote Hosts That Are Not in The Same Network

Usually you can transfer files between remote machines with scp because they are on the same network, with routers between them that route the traffic.

But there are instances where you need to transfer data between remote machines that aren’t on the same network, because there are no routers between them, however you can connect to both of them from your computer.

With scp you have an option to transfer the data through the third machine sending the command, such as your local computer. You can do this with the -3 option.

The following command will copy files from two machines through the machine that is sending the command.

scp -3 [email protected]_host_1:/var/www/file1 [email protected]_host_2:/var/www/file2

Video Demo

An example of the above command.

scp -3 [email protected]:/home/edxd/my_file [email protected]:/home/stelixd
5. SCP Command - Copy Files Across Remote Hosts (Route)

5. Copy Files with Certain Extensions With the SCP Command

To copy files of a specific type you can run a command such as:

scp [email protected]_host:'/directory/*.{html,php}' /destination/folder

Important Note: Please note the pair of single quotes ', along with the * wildcard, and curly braces with comma separated extensions. This will cause the shell to turn the expression into:

scp [email protected]_host:/directory/*.html [email protected]_host:/directory/*.php /destination/folder

6. Copy a Directory Recursively With the SCP Command

To copy a directory along with all its contents, we will include the -r (recursive) parameter in our SCP command. This command will copy a directory and all its contents:

scp -r transfer_folder [email protected]_host:/remote/path/

Let’s copy the transfer_folder directory on our local computer to our remote host.

scp -r transfer_folder [email protected]:/home/stelixd

Video Demo

3. SCP Command - Copy a Directory Recursively

SCP Options

You can easily view scp options in your command-line by running man scp. We’ll explore a few of these options here.

SCP Verbose Mode (-v, -vv, -vvv)

By enabling verbose mode with the scp command, you can see debug information for SCP – essentially you’re seeing everything happening behind the scenes.

The more -v you use, the more verbose the output will be. The maximum number of -v is 3.

Video Demo

For our example we’ll copy a few files movie1.mp4, movie2.mp4, movie3.mp4 and movie4.mp4 using -v.

4. SCP Command - Copy Files Verbose Mode

Transfer and Compress Files on The Fly (-C)

If you are copying a large file or multiple files over a slow network, you can use the -C parameter, which will enable scp to compress the files before transferring them over the internet.

That may also save on your bandwidth if bandwidth is an issue. On reasonably fast connections, this might just slow things down, however.

Note: We have included the -v (verbose) parameter in the command below to see what is happening behind the scenes.

scp -vC example_file [email protected]:/home/stelixd

Video Demo

6. SCP Command - Compress and Copy Files

Limit Bandwidth Usage (-l)

When you’re copying a file from your local computer to a remote host, think of it as an upload process. Now, if the upload bandwidth used by the SCP command is high, it might impact the network or other processes and devices also uploading data.

Luckily, we can use the -l parameter and specify the bandwidth used by the SCP command in Kilobits/sec (kbps).

Important: Even though we specify the transfer rate in Kilobits/sec (kbps), the transfer rate will be displayed in Kilobytes/sec (KB/s). A Kilobyte is made up of 8 Kilobits. So when we specify, say scp -l 1600, we’re saying we want a transfer rate of 1600 Kilobits, which in KB/s means 1600 / 8 = 200 KB/s. As another example, if you want to limit transfer to 300 KB/s, you multiply 300 * 8 = 2400 Kilobits. So we run scp -l 2400.

In the command below, we will set our SCP transfer bandwidth to 800 Kb/s (800 * 8 = 6400 Kilobits/sec).

scp -l 6400 example_file [email protected]:/home/stelixd
7. SCP Command - Limit Bandwidth Usage

Specify Port Number (-P)

By default, SSH uses port 22.

For security reasons and other related measures, some people prefer changing this default port and configuring a custom port to work with the SSh service. You will need to specify the custom SSH port in your SCP command using the -P parameter in such a situation.

We haven’t configured any custom port in our case, and we will just enter port 22.

scp -P 22 example_file [email protected]:/home/stelixd
8. SCP Command - Specify Port Number

Set a Different Cipher (-c)

To copy files securely over a network, scp uses the AES encryption algorithm. To specify a different algorithm, use the -c parameter. For this example, we will use the aes128-ctr cipher. Some ciphers are more secure and others are faster than others.

Note: This -c parameter is a lowercase character, unlike our -C (uppercase) used for file compression.

scp -c aes128-ctr example_file [email protected]:/home/stelixd
9. SCP Command - Set a Different Cipher

Force SCP to Use IPv4 or IPv6 Addresses (-4 / -6)

You can specify whether scp should use IPv4 or IPv6, with the -4 and -6 options.

To use IPv4:

scp -4 /path/to/file1 [email protected]_host:/remote/path/

To use IPv6:

scp -6 /path/to/file1 [email protected]:/remote/path/

Automate File Transfers Using a SCP Shell Script

If you have files or directories that you copy regularly, you can create a simple bash script and save the time of writing those long commands on the terminal.

There are various ways you can write scripts to use the SCP command.

In this example I’ll create a simple script that requests a target file or directory that I manually input, then it loops through some destinations in a file (that I’ve set beforehand), and transfers the file I entered to those destinations.

I created a file called destination_address.txt in the /tmp directory. This text file will hold the [email protected]_address:/destination of our remote host. In this case, I want to transfer files to my remote server, in the ~/remote_transfers folder.

[email protected]:~/remote_transfers/

Now let’s create our bash script:

echo "=================="
echo "Running SCP Script"
echo "=================="
echo -e "Enter the path to the file you wish to copy:\c"
read file

for dest in cat /tmp/destination_address.txt; do
scp -r $file ${dest}

done

We will save our script as scp_script.sh. To make the script executable, remember to run the command chmod +x scp_script.sh.

To run it I’ll run:

sudo bash scp_script.sh
10. SCP Command - Automate File Transfers Using a SCP Shell Script

SSH Key (Identity File) Path (-i) with the SCP Command

If you have configured SSH key-based authentication, you can use the -i option and specify the path to the identity file.

Identity files come in different formats, depending on your setup and environment. For example .pub is the file format used by SSH, .pem can be used for AWS when you created your key-pair.

The following command connects to a remote host using an SSH Key.

scp -i /path/to/ssh_key.pub /path/to/local_file [email protected]_host:path/to/remote/file

Using Multiple SCP Options

You can use multiple options in the same command. Some flags can be combined. If you check man scp you should see the scp full syntax, which should give you a good idea on what flags you can combine:

scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] source ... target

Preserve File Modification/Access Times and Modes With the SCP Command (-p)

To preserve modification times, access times, and modes with scp you can use the -p flag:

scp -p /path/to/example.txt [email protected]:/remote/path

How to Resume Interrupted SCP File Transfers

SCP does not understand range-request or partial transfer, such as HTTP does. As such, scp implementations, such as our command-line utility can’t resume interrupted downloads.

However, there are simple ways to resume interrupted scp transfers, by using other utilities that have this capability.

A very easy and straightforward way of resuming aborted downloads is using the sftp interactive commands reput and reget.

Resume Interrupted File Transfers with SFTP Reget or Reput

SFTP (SSH File Transfer Protocol) is a related secure transfer protocol, which is used to access, manage and transfer files using SSH.

To read more on sftp and its’ options you can run man sftp or read the sftp manual page online.

It works a little different than scp, as it offers an option to run interactive commands after connecting to a remote host.

The two interactive commands that can help us resume interrupted downloads or uploads are:
1. reget: resumes downloads
2. reput: resumes upload

In the following example we start downloading a 700 mebgabyte file called bytexd.txt from a remote server, that we interrupt by pressing Ctrl + C, when it’s at 9%:

scp [email protected]_host:/remote/directory/bytexd.txt bytexd.txt
Output
bytexd.txt 9% 65MB 3.1MB/s 03:34 ETA

To continue the download we’ll have to connect to the remote host using sftp:

sftp [email protected]_host

You will have to authenticate, such as you would with scp or ssh.

When you’re logged in with sftp you’ll notice your prompt has changed into:

sftp>

Now we can run interactive commands.

You can also run commands such as cd and ls to navigate and find your files. Read more on all available interactive commands in the man page.

To resume the download, we’ll run the reget interactive command, followed by the file path on the remote directory:

sftp> reget /remote/directory/bytexd.com
Output
Resuming /remote/directory/bytexd.txt to bytexd.txt
/remote/directory/bytexd.txt 10% 73MB 771.1KB/s 13:53 ETA

Installing SCP (Optional)

On Linux and Mac, scp is usually already installed, and on Windows you’ll most likely have to install it yourself.

Install SCP on Linux

Installing scp will different, depending on your distro.

Install SCP on Debian-based Distros

To install scp on Debian-based distros (such as Debian, Ubuntu, Linux Mint, and others) run:

sudo apt install openssh-client

Install SCP on RHEL-based Distros

To install scp on RHEL-based distros (such as CentOS, Fedora, Rocky Linux, AlmaLinux, and others) run:

sudo dnf install openssh-clients

Install SCP on Windows

SCP doesn’t come installed on Windows so we’ll have to install it ourselves. We’ll cover two common ways. There are probably more out there, but these two are popular and tested.

pscp (Putty) – Windows SCP via Command-line

PSCP (PuTTY Secure Copy) is similar to scp and comes bundled with PuTTY, probably the most used SSH client for Windows. It is free and open-source.

You can download and install Putty from the developer’s (Simon Tatham) website, if you don’t have it already.

You can also download and install pscp.exe separately, if you prefer.

After installing it, open a new command shell (like cmd.exe) and run:

pscp

You should see something like:

PuTTY Secure Copy client
Release 0.74
Usage: pscp [options] [[email protected]]host:source target
       pscp [options] source [source...] [[email protected]]host:target
       pscp [options] -ls [[email protected]]host:filespec
Options:
  -V        print version information and exit
  -pgpfp    print PGP key fingerprints and exit
  -p        preserve file attributes
  -q        quiet, don't show statistics
  -r        copy directories recursively
  -v        show verbose messages
  -load sessname  Load settings from saved session
  -P port   connect to specified port
  -l user   connect with specified username
  -pw passw login with specified password
  -1 -2     force use of particular SSH protocol version
  -4 -6     force use of IPv4 or IPv6
  -C        enable compression
  -i key    private key file for user authentication
  -noagent  disable use of Pageant
  -agent    enable use of Pageant
  -hostkey aa:bb:cc:...
            manually specify a host key (may be repeated)
  -batch    disable all interactive prompts
  -no-sanitise-stderr  don't strip control chars from standard error
  -proxycmd command
            use 'command' as local proxy
  -unsafe   allow server-side wildcards (DANGEROUS)
  -sftp     force use of SFTP protocol
  -scp      force use of SCP protocol
  -sshlog file
  -sshrawlog file
            log protocol details to a file

File path notation is different for Windows that for Linux. With pscp you must specify the file paths appropriately for each operating system.

Copy Files from Windows to Linux with PSCP

To copy files from Windows to Linux, using pscp you can run something like:

pscp c:\path\to\file [email protected]_host:/path/to/file

Copy Files from Linux to Windows with PSCP

To copy files from Linux to Windows using pscp:

pscp [email protected]_host:/path/to/file c:\path\to\file

WinSCP – GUI Version of SCP

WinSCP is a very popular GUI (graphical user interface) software, for Windows, that allows copying files between local and remote hosts, and supports the following file transfer protocols – SCP, FTP, FTPS, SFTP, WebDAV and S3.

It’s very straightforward and easy to use. To install it follow the instructions in the install guide , and you can read about its features and other useful information in the Documentation.

Many Windows users prefer WinSCP since it mainly offers a graphical user interface and offers functionalities such as:

  1. Drag & Drop: Simply using the interface to drag/drop files to copy them from the local to the remote system, and vice versa.
  2. Synchronizing: Which synchronizes content of a local directory onto the remote directory, vice versa, or even full sync which means that any modification made on either system, it will be applied to the other system.
  3. Resuming Transfers
  4. .. many more that you can find in the WinSCP Docs

Conclusion

This post has given you a detailed guide on using the scp command to securely transfer files, and how to use some of the most common options. To easily see all the scp command options, along with their explanations, you can run the man scp command in your command-line, or you can read them online.

If you have any questions or requests, then feel free to let us know in the comments section and we’ll get back to you as soon as we can.

1 Shares:
Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
danny
danny
2 months ago

what console do you use?

You May Also Like
Rm Command in Linux
Read More

Rm Command in Linux

The rm command is a very important command used to remove files and directories in Linux. The rm…