Website Vidya
SecurityStep-by-Step Guide

scp Command in Linux: Secure File Transfer Examples and Syntax

Learn scp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
scp Command in Linux: Secure File Transfer Examples and Syntax
AI Executive SummaryWebsiteVidya AI

9 min read

Learn scp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What scp Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The scp command in linux is the classic, universally recognized utility for copying files securely across network boundaries. Distributed as an integral component of the OpenSSH suite, scp replaced the historical rcp (remote copy) utility by encapsulating all data transmissions within authenticated, encrypted SSH transport tunnels.

Whether deploying application configuration files to remote virtual machines, pulling database backups from a production server to an offsite workstation, or staging assets across cloud environments, scp provides an intuitive syntax modeled after the standard POSIX cp command. By leveraging existing SSH key pairs, ssh-agent keyrings, and ~/.ssh/config profiles, scp executes remote file transfers without requiring separate daemon configurations or open FTP ports.

Modern OpenSSH releases (version 9.0 and later) have modernized scp: while retaining the classic command-line flags and argument grammar, modern scp uses the secure SFTP protocol under the hood by default, resolving historical vulnerabilities associated with legacy RCP wire protocol parsing.

Advertisement
scp Command in Linux: Secure File Transfer Examples and Syntax — syntax, flags, and practical terminal workflow diagram
scp Command in Linux: Secure File Transfer Examples and Syntax — command syntax, key options, and production workflow reference.

What scp Does and When to Use It

Under the hood, scp initiates an encrypted SSH-2 connection over TCP port 22, completing cryptographic host key verification and user authentication (via public key or password). In legacy implementations, scp invoked a remote rcp server process over the SSH channel, which suffered from wildcard expansion ambiguities and quoting vulnerabilities (such as CVE-2019-6111).

In modern OpenSSH (9.0+), scp functions as an SFTP client by default. When you run scp, it requests the sftp subsystem on the remote SSH daemon, transferring files via structured binary SFTP protocol packets. If communicating with an older server that lacks an SFTP subsystem, scp can fall back to the legacy SCP wire protocol using the -O option. Data transferred over the wire is encrypted using modern ciphers like ChaCha20-Poly1305 or AES-GCM.

At the operating system level, scp interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running scp in cloud instances or Kubernetes worker nodes, combining flags such as -P PORT, -i KEY, -r, -p lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The scp utility is packaged in openssh-client across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether scp is installed and inspect which binary path and version your shell resolves:

type -a scp
scp --version 2>/dev/null || man -f scp

# Illustrative output (reviewed against documentation)
scp is /usr/bin/scp
scp (openssh-client)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y openssh-client

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y openssh-clients

# Arch Linux
sudo pacman -S --noconfirm openssh

# Alpine Linux
sudo apk add --no-cache openssh-client

Command Syntax, Arguments, and Exit Status Codes

scp [OPTIONS] [[user@]host1:]file1 ... [[user@]host2:]file2

The scp syntax follows: scp [OPTIONS] SOURCE DESTINATION. Paths can be local filesystem paths (e.g., /path/to/file) or remote paths formatted as [user@]host:/path/to/destination. If the user@ prefix is omitted, scp defaults to the currently logged-in local username.

Important command options include -P PORT (specifies custom SSH port; note uppercase -P, distinct from ssh's lowercase -p), -i KEYFILE (specifies private identity key), -r (copies directories recursively), -p (preserves modification times, access times, and file modes), -C (enables gzip compression in transit), and -l LIMIT (throttles bandwidth in Kbit/s).

  • 0 — Successful execution; all specified files and directories were copied completely.
  • 1 — Operational error; connection refused, authentication failed, file not found, or permission denied.
  • 2 — Command-line syntax error or invalid argument supplied.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-P PORT--portSpecifies the remote SSH port number to connect to (note uppercase -P).
-i KEY--identitySelects the private key file (identity file) used for public key authentication.
-r--recursiveRecursively copies entire directory trees and their contents.
-p--preservePreserves file modification times, access times, and permission modes from the source.
-C--compressEnables transparent compression on the SSH transport stream to accelerate transfers.
-q--quietQuiet mode; suppresses progress meters, transfer speed statistics, and diagnostic messages.
-v--verboseEnables verbose debugging output, showing SSH connection, cipher negotiation, and authentication.
-l LIMIT--limitLimits transfer bandwidth consumption to LIMIT kilobits per second (Kbit/s).
-O--legacy-protocolForces scp to use the legacy SCP wire protocol instead of the modern SFTP protocol.

A common source of confusion is the port option: OpenSSH's ssh command uses lowercase -p for port, whereas scp uses uppercase -P for port (reserving lowercase -p for 'preserve file attributes'). Running scp -p 2222 will mistakenly attempt to preserve attributes on a nonexistent file named '2222'.

Advertisement

For directory synchronization, pairing -r with -p and -C (e.g., scp -rpC ./build/ user@server:/var/www/) preserves accurate timestamps and accelerates transfers over WAN connections by compressing compressible text, HTML, and script assets in flight.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Copy a Local File to a Remote Server

Transfer a configuration file from your local machine to a remote server's home directory.

scp nginx.conf [email protected]:/etc/nginx/

# Illustrative output (reviewed against documentation)
nginx.conf                                    100% 2450     1.2MB/s   00:00

scp establishes an SSH connection, authenticates, and copies nginx.conf to /etc/nginx/ on the remote server.

2. Copy a Remote File to the Local Machine

Download a remote database backup file to your current local directory.

scp [email protected]:/var/backups/db_backup.sql.gz ./

# Illustrative output (reviewed against documentation)
db_backup.sql.gz                              100%   45MB  14.8MB/s   00:03

Reversing the arguments downloads the remote file to the local directory (represented by .).

3. Copy an Entire Directory Recursively Preserving Timestamps

Recursively upload an entire website assets folder while maintaining original modification times and file permissions.

scp -r -p ./assets [email protected]:/var/www/html/

# Illustrative output (reviewed against documentation)
logo.png                                      100%  120KB   4.2MB/s   00:00    
style.css                                     100%   24KB   1.8MB/s   00:00    
app.js                                        100%   85KB   3.5MB/s   00:00

The -r flag traverses subdirectories, and -p preserves timestamps and permission bits across all transferred files.

4. Transfer Files Using Custom SSH Port and Private Key

Connect to a hardened server running on custom port 2222 using a specific Ed25519 identity key.

scp -P 2222 -i ~/.ssh/deploy_ed25519 release.tar.gz [email protected]:/opt/releases/

# Illustrative output (reviewed against documentation)
release.tar.gz                                100%   12MB  11.2MB/s   00:01

The uppercase -P 2222 routes to the non-standard SSH port, and -i supplies the private key for authentication.

5. Copy Files Directly Between Two Remote Servers

Transfer a file directly from server A to server B through your local administrative workstation.

scp [email protected]:/data/report.csv [email protected]:/data/

# Illustrative output (reviewed against documentation)
report.csv                                    100%  512KB   2.4MB/s   00:00

scp tunnels data between host1 and host2, using your local workstation as the authenticated routing conduit.

6. Limit Bandwidth Consumption to Prevent Network Saturation

Cap transfer speed to 8000 Kbit/s (approx. 1 MB/s) during large file transfers across office networks.

scp -l 8000 disk_image.raw [email protected]:/storage/

# Illustrative output (reviewed against documentation)
disk_image.raw                                 15%  150MB 980.0KB/s   01:25 ETA

The -l 8000 option limits bandwidth to 8000 Kbit/s, ensuring other network applications are not starved of bandwidth.

Real-World Workflows, Pipelines, and Shell Automation

Automated Deployment Artifact Publishing Pipeline

Integrate scp into a CI/CD build script to securely copy compiled distribution archives to staging servers.

#!/usr/bin/env bash
set -euo pipefail

ARTIFACT="dist/app-v2.0.tar.gz"
REMOTE_USER="deploy"
REMOTE_HOST="staging.example.com"
REMOTE_DIR="/var/www/staging"
KEY_FILE="~/.ssh/ci_deploy_key"

echo "=== Verifying Build Artifact ==="
if [ ! -f "${ARTIFACT}" ]; then
  echo "Error: Artifact ${ARTIFACT} does not exist!"
  exit 1
fi

echo "=== Uploading Artifact to ${REMOTE_HOST} ==="
scp -i "${KEY_FILE}" -p -C "${ARTIFACT}" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/"

echo "=== Extracting Artifact on Remote Server ==="
ssh -i "${KEY_FILE}" "${REMOTE_USER}@${REMOTE_HOST}" "
  tar -xzf ${REMOTE_DIR}/app-v2.0.tar.gz -C ${REMOTE_DIR}/
  sudo systemctl restart app.service
"
echo "Deployment completed successfully."

# Illustrative output (reviewed against documentation)
=== Verifying Build Artifact ===
=== Uploading Artifact to staging.example.com ===
app-v2.0.tar.gz                               100%   18MB  12.4MB/s   00:01    
=== Extracting Artifact on Remote Server ===
Deployment completed successfully.

This production pipeline uploads an application archive using scp with compression (-C) and executes remote deployment commands via ssh.

Remote Database Backup Extraction and Local Archive Verification

Securely pull compressed database snapshots from a remote database node to local cold storage, validating transfer integrity.

#!/usr/bin/env bash
set -euo pipefail

REMOTE_SERVER="db.example.com"
REMOTE_FILE="/var/backups/postgres-daily.sql.gz"
LOCAL_DIR="/backups/database"
DATE_STAMP=$(date +%Y%m%d)
TARGET_FILE="${LOCAL_DIR}/postgres-${DATE_STAMP}.sql.gz"

mkdir -p "${LOCAL_DIR}"

echo "=== Downloading Database Backup from ${REMOTE_SERVER} ==="
scp "backup@${REMOTE_SERVER}:${REMOTE_FILE}" "${TARGET_FILE}"

echo "=== Verifying Gzip Archive Integrity ==="
if gzip -t "${TARGET_FILE}"; then
  echo "INTEGRITY CHECK PASSED: Backup archive is valid and uncorrupted."
else
  echo "ERROR: Backup archive is corrupted!"
  exit 1
fi

# Illustrative output (reviewed against documentation)
=== Downloading Database Backup from db.example.com ===
postgres-daily.sql.gz                         100%  340MB  24.1MB/s   00:14    
=== Verifying Gzip Archive Integrity ===
INTEGRITY CHECK PASSED: Backup archive is valid and uncorrupted.

The script downloads a database backup with scp and immediately runs gzip -t to confirm the archive was not corrupted during transit.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding scp inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Always configure SSH key pair authentication (using Ed25519 or RSA-4096 keys) and disable root password logins on target servers. When scripting scp in automated environments, use dedicated deploy keys with restricted permissions.

Legacy versions of scp were vulnerable to remote shell injection when handling unescaped wildcards or special characters in filenames (CVE-2019-6111). Ensure your servers run modern OpenSSH (9.0+) where scp defaults to the safe SFTP protocol backend.

GNU/Linux, BSD, and BusyBox Implementation Differences

The scp utility is pre-installed across all Linux distributions, macOS, FreeBSD, and modern Windows 10/11 (via OpenSSH for Windows). Command syntax is uniform across all platforms.

Unlike rsync, scp cannot perform delta transfers (syncing only changed blocks) or resume interrupted transfers. For synchronizing large directory trees or resuming severed downloads, rsync or sftp is preferred over scp.

Troubleshooting Common Errors and Diagnostics

Permission denied (publickey,password)

Root Cause: SSH authentication failed because the public key is not listed in ~/.ssh/authorized_keys on the remote server.

Resolution: Verify user credentials, specify the correct identity key with -i, or copy the key using ssh-copy-id.

scp -i ~/.ssh/id_ed25519 file.txt user@remote-host:/path/

ssh: connect to host ... port 22: Connection refused

Root Cause: The remote SSH daemon is listening on a non-standard port or blocked by a firewall.

Resolution: Specify the correct port using uppercase -P (e.g., -P 2222).

scp -P 2222 file.txt user@remote-host:/path/

scp: /path/file: No such file or directory

Root Cause: The target destination directory does not exist on the remote host (scp does not create parent directories automatically).

Resolution: Create the destination directory on the remote host with ssh user@host 'mkdir -p /path' prior to copying.

ssh user@remote-host "mkdir -p /target/dir"
scp file.txt user@remote-host:/target/dir/

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
scp copies entire files from source to destination every time. rsync uses a delta-transfer algorithm to copy only modified blocks, supports transfer resumption, and can delete extraneous destination files to maintain exact mirrors.
No. scp cannot resume broken transfers; if a transfer is interrupted, rerun the command to start copying from byte zero. To resume partial transfers, use rsync -P or sftp (reget).
Because lowercase -p was already reserved to mean 'preserve file attributes' (modification times and permissions). Uppercase -P was assigned for port number specification.
List multiple files separated by spaces before the final remote destination argument: scp file1.txt file2.txt file3.txt user@remote-host:/var/data/.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout