Bash Secure Copy

scp copies files and directories to and from remote machines over the same encrypted connection that SSH uses.

#Jobseeker

Find matching jobs & Auto apply with AI

Hyring
Jobseeker using Hyring to search, apply, and prepare with AI

What Is scp?

scp (secure copy) moves files between your local machine and a remote host, or between two remote hosts, encrypting the transfer using the SSH protocol. The syntax mirrors the local cp command, just with a user@host: prefix added to whichever side is remote.

Copying a File to a Remote Server

To upload a file, put the local path first and the remote destination, prefixed with user@host:, second. If you leave off a filename on the remote side, scp keeps the original name and places it in that directory.

Uploading a File

$ scp ./deploy.tar.gz deploy@203.0.113.42:/var/www/releases/
deploy.tar.gz                  100%   84MB  22.4MB/s   00:03

Copying a File From a Remote Server

Reverse the order to download instead: the remote path comes first, and the local destination, which can be . for the current directory, comes second.

Downloading a File

$ scp deploy@203.0.113.42:/var/log/nginx/access.log ./logs/
access.log                     100%  2.1MB  15.9MB/s   00:00

Copying Whole Directories and Using Custom Ports

Add -r to copy a directory recursively, and -P (capital P, unlike ssh's lowercase -p) to target a non-standard port. You can also add -i to authenticate with a specific private key, just like with ssh.

Recursive Copy on a Custom Port

$ scp -r -P 2222 ./site-backup deploy@203.0.113.42:/home/deploy/backups/
site-backup/index.html          100%  4.2KB   3.1MB/s   00:00
site-backup/style.css           100%  1.8KB   1.4MB/s   00:00
site-backup/images/logo.png     100%   96KB   9.5MB/s   00:00
  • -r - copy directories recursively
  • -P <port> - connect on a non-default SSH port (capital P)
  • -i <keyfile> - authenticate with a specific private key
  • -p - preserve modification times and permissions from the source
  • -C - compress data during the transfer, useful on slow links
Note: scp can copy directly between two remote servers, for example scp userA@hostA:/file userB@hostB:/dest, without ever needing a local copy of the file.
Note: For syncing large or frequently changing directory trees, rsync -avz -e ssh is usually a better fit than scp since it only transfers the differences between runs.

Exercise: Bash Networking

What is the primary purpose of the "ping" command?