Copying over the network: scp

scp copies files securely between your machine and a remote server over SSH.

Syntaxscp [-r] source destination

scp (secure copy) transfers files over the same encrypted SSH connection. The syntax mirrors cp, except a remote location is written as user@host:/path.

Which way?

  • Upload: local path first, remote second.
  • Download: remote path first, local second.
  • Add -r to copy a whole directory.

For repeated syncing, many people prefer rsync, which only transfers the parts of files that changed.

Example

Example Β· bash
# Upload a file to the server
scp report.pdf [email protected]:/home/alice/

# Download a file from the server
scp [email protected]:/var/log/app.log ./

# Copy an entire folder up
scp -r ./website [email protected]:/var/www/

# Efficient repeat sync with rsync
rsync -av ./website/ [email protected]:/var/www/

When to use it

  • A developer uploads a build artifact to a staging server with 'scp dist/app.tar.gz deploy@staging:/opt/releases/'.
  • A sysadmin downloads a database dump from a remote server with 'scp user@dbserver:/tmp/backup.sql.gz ./' for local inspection.
  • A team copies config files between two remote servers with 'scp -3 server1:/etc/app/config.yaml server2:/etc/app/'.

More examples

Copy file to remote server

Shows the scp command for uploading a file; the path syntax is user@host:/remote/path.

Example Β· bash
# Upload a local file to a remote path
scp ./dist/app.tar.gz [email protected]:/opt/releases/

# Upload with a specific SSH key
scp -i ~/.ssh/deploy_key build.zip user@server:/tmp/

Download file from remote

Reverses the direction to download, and uses -r to recursively copy an entire directory.

Example Β· bash
# Download a remote file to current directory
scp [email protected]:/var/log/nginx/access.log ./

# Download directory recursively
scp -r [email protected]:/etc/nginx/ ./nginx_backup/

Copy between two remote hosts

Uses -3 to copy between two remote servers routing through the local machine, avoiding direct server-to-server auth setup.

Example Β· bash
# -3 routes data through local machine
scp -3 [email protected]:/etc/app/config.yaml \
       [email protected]:/etc/app/config.yaml

Discussion

  • Be the first to comment on this lesson.