Linux commands
Browse topics

Copying files between hosts with scp and sftp

Version
unversioned
Review
Draft

Summary#

scp copies files over SSH. A remote file is written as user@host:path. sftp opens an interactive file transfer session over the same protocol.

Syntax#

sh
scp report.pdf deploy@server.example.test:/srv/reports/
scp deploy@server.example.test:/var/log/app.log .
scp -r site deploy@server.example.test:/srv/
scp -P 2222 -i "$key" file preview:/tmp/
sftp deploy@server.example.test

-r copies directories, -P sets the port with a capital letter and -i selects a key. Host aliases from ~/.ssh/config work as they do with ssh.

Example#

This example runs offline. It starts a private SSH server through ProxyCommand, with temporary keys, and does not read your SSH configuration. It needs the OpenSSH server program and an account that is allowed to log in with a key.

sh
(
  set -eu
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  sshd=$(command -v sshd || echo /usr/sbin/sshd)
  ssh-keygen -q -t ed25519 -N '' -f "$dir/host"
  ssh-keygen -q -t ed25519 -N '' -f "$dir/user"
  printf '%s\n' \
    "HostKey $dir/host" \
    "AuthorizedKeysFile $dir/user.pub" \
    'PidFile none' \
    'UsePAM no' \
    'StrictModes no' \
    'Subsystem sftp internal-sftp' > "$dir/sshd_config"
  echo 'copied over SSH' > "$dir/source.txt"

  scp -q -F /dev/null -i "$dir/user" -o IdentitiesOnly=yes \
    -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR \
    -o "ProxyCommand=$sshd -i -f $dir/sshd_config -E $dir/sshd.log" \
    "$dir/source.txt" "$(id -un)@local-demo:$dir/copied.txt"
  cat "$dir/copied.txt"
)

Expected output#

Text
copied over SSH

Common mistakes#

The port option is -P for scp and sftp but -p for ssh; scp -p preserves times and modes. Forgetting the colon after the host copies to a local file with that name. An existing destination file is overwritten without asking. Turning host key checking off is acceptable only for the throwaway server in this example; keep it on for real hosts. Use rsync to resume large transfers or to copy only changes.

Version applicability#

This entry describes OpenSSH 10. Since OpenSSH 9.0, scp uses the SFTP protocol by default, so remote wildcards and quoting can behave differently from older releases.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0