Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 3 · Networking and hardening · Lesson 05 · 35 minutes

Copy files safely with scp

After this lesson you can
  • Copy a file and a folder to and from a server with scp
  • Use another port and a named key, and prove that a copy is identical
  • Say what the known-hosts warning means, and say when sftp or rsync is the better tool
Lab files of this lesson (4)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

You must put the report folder of the week on the test server, and bring one data file back for the analysts. Your team lead adds: "Show me that the file that arrived is the file that left." You use scp, which copies over the encrypted SSH connection that you built in lesson 4, and you prove the result with a checksum.

Recall

Which file on the server holds the public keys that may log in to an account?

~/.ssh/authorized_keys of that account. The folder ~/.ssh has mode 700 and the file 600.

Which mode must a private key have, and what does ssh do if others can read the key?

600. ssh refuses to use the key.

The idea

scp (secure copy) copies files between two machines. It opens an SSH connection, logs in as the account that you name, and sends the file through it. So everything that you set for SSH holds for scp: the same accounts, the same keys, and the same host-key check. A remote place is written USER@HOST:PATH. A path without a leading slash starts in the home folder of that account. The first argument is the source and the last one is the destination.

How scp copies a file
scpsshsshdFilestart a connection to the serverlog in with the keysend report.txt through itwrite /tmp/report.txtdone, exit code 0scpsshsshdFile12345
  1. scp → ssh: start a connection to the server
  2. ssh → sshd: log in with the key
  3. scp → sshd: send report.txt through it
  4. sshd → File: write /tmp/report.txt
  5. sshd → scp: done, exit code 0
An scp command
scpsecure copy-P 2222the port (capital P)-i lab_keythe private keyreport.txtthe source: a local filekr_ops@localhost:/tmp/report.txtthe target: USER@HOST:PATHscpsecure copy-P 2222the port (capital P)-i lab_keythe private keyreport.txtthe source: a local filekr_ops@localhost:/tmp/report.txtthe target: USER@HOST:PATH
TaskForm
Upload a filescp FILE USER@HOST:PATH
Download a filescp USER@HOST:PATH FILE
Copy a folderadd -r (recursive)
Another port-P PORT, with a capital P
A named key-i KEYFILE
Keep times and modes-p

The capital -P is a trap: ssh uses a small -p for the port, and scp uses -p for "preserve".

Worked example

Lesson 4 left the server on the loopback only, with key login only and kr_ops as the only allowed account. Use that server. Step 1 moves it to another port.

1. Move the server to port 2222

Port 22 is where every scan looks first. Another port only removes the noise of bots that try port 22: it does not stop a scan of all ports. The option Port sets it. Save the drop-in file again, in the lab folder ssh, with the line Port 2222 added. Copy it, check it, restart the server and look at the listener. The ssh option -p picks the port.

cd ~/krlab/linux-advanced/ssh

01-krlab.conf

ListenAddress 127.0.0.1
Port 2222
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AllowUsers kr_ops
sudo systemctl enable --now ssh
sudo cp 01-krlab.conf /etc/ssh/sshd_config.d/01-krlab.conf
sudo sshd -t
sudo systemctl restart ssh
ss -tln | grep -E ':(22|2222) '
ssh -p 22 -i lab_key kr_ops@localhost id -un
ssh -p 2222 -i lab_key kr_ops@localhost id -un
LISTEN 0      128        127.0.0.1:2222      0.0.0.0:*
ssh: connect to host localhost port 22: Connection refused
kr_ops

A new port is a new entry in known_hosts. If ssh asks the host-key question again on port 2222, answer yes.

If the last line is an error instead of kr_ops (a new day, a restored snapshot), run this block once, and then the last ssh command again. install copies a file and sets its mode and owner in one step, and install -d makes a folder in the same way.

sudo useradd -m -s /bin/bash kr_ops
sudo install -d -m 700 -o kr_ops -g kr_ops /home/kr_ops/.ssh
sudo install -m 600 -o kr_ops -g kr_ops ~/krlab/linux-advanced/ssh/lab_key.pub /home/kr_ops/.ssh/authorized_keys
sudo cp ~/krlab/linux-advanced/ssh/01-krlab.conf /etc/ssh/sshd_config.d/
sudo systemctl disable --now ssh.socket
sudo systemctl restart ssh

2. Read the known-hosts warning

The saved host key of a server is checked at every login. Make a known_hosts file that holds a wrong key for this server, and connect with it. -o UserKnownHostsFile=FILE names the file to use, so your real file stays untouched. A server on another port is saved as [HOST]:PORT. A new key stands for the wrong key: ssh-keygen -q makes it without messages (-q is quiet), and cut -d' ' -f1,2 keeps the first two fields of its public line, the key type and the key, without the comment.

ssh-keygen -q -t ed25519 -f fake -N ""
echo "[localhost]:2222 $(cut -d' ' -f1,2 fake.pub)" > kh
ssh -p 2222 -i lab_key -o UserKnownHostsFile=kh kr_ops@localhost id -un
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Offending ED25519 key in kh:1
Host key verification failed.

The saved key and the key that the server shows differ. Either the server was reinstalled and made a new key, or someone sits between you and the server. Do not delete the line before you know which: compare the fingerprint with the one of the owner (ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub on the server). For a known change, ssh-keygen -f kh -R '[localhost]:2222' removes the old line.

3. Make a file

KEY is a shell variable that holds the path of the private key of lesson 4, so that the commands stay short. printf prints text with line ends that you write as \n. wc -c counts bytes.

KEY=~/krlab/linux-advanced/ssh/lab_key
mkdir -p ~/krlab/linux-advanced/scp && cd ~/krlab/linux-advanced/scp
printf 'quarterly report\nstatus: green\n' > report.txt
wc -c report.txt
31 report.txt

4. Upload a file

The file goes to /tmp on the server, under the name report.txt. In a terminal, scp shows a progress line such as report.txt 100% 31 ...; -q hides it. Ask the server for the file to see that it is there. sha256sum prints a hash of the contents: two files with the same hash have the same bytes.

scp -P 2222 -i "$KEY" report.txt kr_ops@localhost:/tmp/report.txt
ssh -p 2222 -i "$KEY" kr_ops@localhost 'ls -l /tmp/report.txt; sha256sum /tmp/report.txt'
sha256sum report.txt
-rw-rw-r-- 1 kr_ops kr_ops 31 Nov 21 11:23 /tmp/report.txt
82f9a66977baa72d2803b45884d252fca06e353faa2cc6a28c4379e8f1e7185a  /tmp/report.txt
82f9a66977baa72d2803b45884d252fca06e353faa2cc6a28c4379e8f1e7185a  report.txt

The hashes are the same, so the file that arrived is the file that left. The owner on the server is kr_ops, because that is the account that wrote it.

5. Download a file

Swap the two arguments: the remote file is the source. cmp compares two files byte by byte, prints nothing when they are the same, and sets the exit code to 0.

scp -P 2222 -i "$KEY" kr_ops@localhost:/tmp/report.txt back.txt
cmp report.txt back.txt && echo identical
identical

6. Copy a folder

Without -r, scp refuses a folder. With -r, it copies the folder and everything below it. Make a small tree first.

mkdir -p project/docs
echo "readme" > project/README
echo "guide" > project/docs/guide.txt
scp -P 2222 -i "$KEY" project kr_ops@localhost:/tmp/project
scp -r -P 2222 -i "$KEY" project kr_ops@localhost:/tmp/project
ssh -p 2222 -i "$KEY" kr_ops@localhost 'find /tmp/project | sort'
scp -r -P 2222 -i "$KEY" kr_ops@localhost:/tmp/project ./copy
find copy | sort
scp: local "project" is not a regular file
scp: failed to upload file project to /tmp/project
/tmp/project
/tmp/project/docs
/tmp/project/docs/guide.txt
/tmp/project/README
copy
copy/docs
copy/docs/guide.txt
copy/README

Mind the destination. If /tmp/project already exists, the second command makes /tmp/project/project. If it does not exist, the folder is copied to that name. Run find on the result and look.

7. Read the errors

Three failures show you what scp says. The wrong port, no key, and a folder that you may not write to.

scp -P 22 -i "$KEY" report.txt kr_ops@localhost:/tmp/x.txt; echo "exit: $?"
scp -P 2222 report.txt kr_ops@localhost:/tmp/x.txt; echo "exit: $?"
scp -P 2222 -i "$KEY" report.txt kr_ops@localhost:/root/x.txt; echo "exit: $?"
ssh: connect to host localhost port 22: Connection refused
scp: Connection closed
exit: 255
kr_ops@localhost: Permission denied (publickey).
scp: Connection closed
exit: 255
scp: dest open "/root/x.txt": Permission denied
scp: failed to upload file report.txt to /root/x.txt
exit: 1

Exit code 255 means that the connection failed, and 1 means that the transfer failed after the login. A script should check both. scp also replaces an existing file without a question, so check the destination name.

8. Name sftp and rsync

sftp is an interactive file-transfer session over SSH: you list, change folders, and use get and put. rsync -av -e 'ssh -p 2222 -i KEY' SOURCE/ USER@HOST:DEST/ copies over SSH too, but it sends only what changed. -a (archive) keeps modes and times and copies folders, -v lists the files, and -e names the remote shell. A slash at the end of the source copies the content of the folder; without it, rsync copies the folder itself into the destination, the trap that scp -r has too. Run the same rsync twice, and the second run sends no files:

rsync -av -e "ssh -p 2222 -i $KEY" project/ kr_ops@localhost:/tmp/rs/
rsync -av -e "ssh -p 2222 -i $KEY" project/ kr_ops@localhost:/tmp/rs/
sending incremental file list
created directory /tmp/rs
./
README
docs/
docs/guide.txt

sent 236 bytes  received 95 bytes  662.00 bytes/sec
total size is 13  speedup is 0.04
sending incremental file list

sent 127 bytes  received 13 bytes  93.33 bytes/sec
total size is 13  speedup is 0.09

Use scp for one file or one folder, sftp when you must browse, and rsync for backups and large trees that you repeat. rsync is in the package rsync.

Your turn

Do the task of your team lead with new data. There are no steps here: use the commands of the worked example. The server runs on port 2222 and KEY holds the path of the key.

Build a report folder in ~/krlab/linux-advanced/scp-task: the file reports/nums.txt with the numbers 1 to 100, one on each line (seq 1 100), and the file reports/q1/summary.txt with the one line q1: ok.

  1. Make the folder /tmp/kr_in on the server (run mkdir through ssh).
  2. Copy the whole folder reports into /tmp/kr_in on the server.
  3. Fetch /tmp/kr_in/reports/nums.txt back as nums-back.txt, and compare it with the original.

Last, clean up the lab. Delete the test files on the server, stop the service, delete the account and the drop-in file. If userdel says that the account is in use, wait a few seconds and run it again.

ssh -p 2222 -i "$KEY" kr_ops@localhost 'rm -rf /tmp/kr_in /tmp/project /tmp/rs /tmp/report.txt'
sudo systemctl disable --now ssh
sudo userdel -r kr_ops
sudo rm /etc/ssh/sshd_config.d/01-krlab.conf

Check yourself

You type "scp -p 2222 file user@host:/tmp" and get an odd error. What is wrong?

scp uses -P for the port. -p means "preserve times and modes", so 2222 is read as the first file name. ssh uses the small -p for the port, and scp uses the capital -P.

How do you prove that a file arrived unchanged?

Compute a hash on both sides, with sha256sum, and compare. SSH already protects the transfer from change, but a hash also finds a full disk, an interrupted copy or a wrong file.

"scp -r project host:/tmp/project" is run twice. What is different the second time?

The first run creates /tmp/project. The second run finds the folder and puts the copy inside it, as /tmp/project/project. Name the destination folder that already exists, and not the new name, to avoid this.

Why can you not use scp for a server that has only "PasswordAuthentication no" and no key of yours?

scp uses the same login as ssh. Without an accepted key or password, the login fails and nothing is copied. Fix the login first.

"REMOTE HOST IDENTIFICATION HAS CHANGED" appears for a server that you know. What do you do?

Find out why the key changed before you remove the old line. A reinstall explains it. If no one changed the server, the warning can be an attack in the middle: compare the fingerprint over a second channel.

Field notes

  • Since OpenSSH 9 the program scp uses the SFTP protocol inside. The old protocol had weaknesses with file names. The command line is the same, but some old tricks that relied on the remote shell, such as a variable like $HOME in a remote path, no longer work.
  • Quote a remote path that holds a space: scp host:"/tmp/my file" .. Only scp -O needs quotes twice.
  • rsync --dry-run (or -n) shows what it would do and changes nothing. Use it before --delete, which removes files at the destination.
  • Do not put a password in a script. Use a key with command= and from= limits in authorized_keys for an automatic transfer, so that the key can do one job only.
  • Copy a secret over SSH, not through a chat or a mail, and delete the copies when the work is done.