TExcelTAD
Home › Linux & Bash › ssh & scp

ssh & scp

ssh (Secure Shell) gives you an encrypted terminal on a remote machine. It's how you administer cloud servers, deploy code and reach Git hosts. Its companions scp and rsync copy files over the same secure connection.

Note: The example sandbox has no network and no SSH client, so sessions are shown with sample output. The runnable examples work with SSH's configuration files, which you can practise on safely.

Connecting

bash
ssh ada@203.0.113.10               # user@host
ssh -p 2222 ada@server.example.com  # non-standard port
ssh ada@server 'df -h /'            # run one command and return
exit                                # (or Ctrl+D) leave the remote shell

The first time you connect, ssh shows the server's fingerprint and asks whether to trust it:

text
The authenticity of host 'server.example.com (203.0.113.10)' can't be established.
ED25519 key fingerprint is SHA256:Hq3mXb9P0s3kUe1q2V7n3w0yM5cLr4Tg8xZ6aKpQe1E.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'server.example.com' (ED25519) to the list of known hosts.

The answer is stored in ~/.ssh/known_hosts. If that key ever changes unexpectedly, ssh refuses to connect with a big warning, because it could mean someone is intercepting the connection.

Key-based login

Passwords can be guessed; keys can't, realistically. You generate a key pair once: the private key stays on your machine, the public key goes on every server you want to reach.

bash
ssh-keygen -t ed25519 -C "ada@laptop"     # creates ~/.ssh/id_ed25519 and id_ed25519.pub
ssh-copy-id ada@server.example.com        # appends the public key to the server's ~/.ssh/authorized_keys
ssh ada@server.example.com                # now logs in without a password
File Where Permissions
~/.ssh/ both 700
~/.ssh/id_ed25519 your machine (private, never share!) 600
~/.ssh/id_ed25519.pub your machine (public) 644
~/.ssh/authorized_keys server: keys allowed to log in 600
~/.ssh/config your machine: host shortcuts 600

SSH refuses to use a private key that other users can read. Setting up the directory with the right permissions:

bash · try it yourself
mkdir -p ~/.ssh
chmod 700 ~/.ssh
printf 'FAKE PRIVATE KEY FOR PRACTICE\n' > ~/.ssh/id_ed25519
printf 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample ada@laptop\n' > ~/.ssh/id_ed25519.pub
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
stat -c '%a %n' ~/.ssh/id_ed25519 ~/.ssh/id_ed25519.pub
cut -d' ' -f1,3 ~/.ssh/id_ed25519.pub
600 /home/learner/.ssh/id_ed25519
644 /home/learner/.ssh/id_ed25519.pub
ssh-ed25519 ada@laptop

A public key line has three parts: the type, the key data and a comment (usually user@machine).

The config file: shortcuts for hosts

Instead of typing ssh -p 2222 -i ~/.ssh/work_key deploy@203.0.113.50 every time, describe the host once in ~/.ssh/config and type ssh prod:

bash · try it yourself
mkdir -p ~/.ssh && chmod 700 ~/.ssh
cat > ~/.ssh/config <<'CFG'
Host prod
    HostName 203.0.113.50
    User deploy
    Port 2222
    IdentityFile ~/.ssh/work_key

Host staging
    HostName staging.example.com
    User deploy

Host github.com
    User git
    IdentityFile ~/.ssh/id_ed25519
CFG
chmod 600 ~/.ssh/config
awk '$1 == "Host" { host = $2 }
     $1 == "HostName" { printf "%-10s -> %s\n", host, $2 }' ~/.ssh/config
grep -c '^Host ' ~/.ssh/config
prod       -> 203.0.113.50
staging    -> staging.example.com
3

The awk script lists which address each alias points to. ssh -G prod prints the full effective settings for an alias, a handy way to debug a config.

Copying files: scp and rsync

bash
scp report.pdf prod:/home/deploy/              # upload a file
scp prod:/var/log/app.log ./                   # download a file
scp -r site/ prod:/var/www/                    # copy a directory
rsync -avz --delete site/ prod:/var/www/site/  # sync: only changed files are sent

scp uses the same user@host:path syntax as ssh (and the same aliases). For repeated copies, rsync is better: it sends only the differences, can resume, and --delete makes the destination an exact mirror. Try rsync --dry-run (-n) first to see what it would do. Its decision is easy to model with two sorted file lists and comm, which prints lines unique to the first file (-23) or to the second (-13):

bash · try it yourself
mkdir -p site/css mirror
echo "home" > site/index.html
echo "body{}" > site/css/main.css
echo "stale" > mirror/old.html
(cd site && find . -type f | sort) > source.lst
(cd mirror && find . -type f | sort) > dest.lst
echo "would send:"
comm -23 source.lst dest.lst
echo "would delete with --delete:"
comm -13 source.lst dest.lst
would send:
./css/main.css
./index.html
would delete with --delete:
./old.html

The real rsync also compares sizes and modification times to skip files that are already up to date.

Hardening a server (concept)

Typical lines in the server's /etc/ssh/sshd_config, applied with sudo systemctl reload ssh:

text
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers deploy ada

Checking such a file is a great job for grep:

bash · try it yourself
cat > sshd_config <<'CFG'
Port 22
PermitRootLogin no
PasswordAuthentication yes
PubkeyAuthentication yes
CFG
for setting in "PermitRootLogin no" "PasswordAuthentication no"; do
  if grep -qx "$setting" sshd_config; then echo "PASS  $setting"; else echo "FAIL  expected: $setting"; fi
done
PASS  PermitRootLogin no
FAIL  expected: PasswordAuthentication no

Test yourself

Which file must NEVER be copied to a server or shared?

  1. ~/.ssh/id_ed25519.pub
  2. ~/.ssh/id_ed25519
  3. ~/.ssh/known_hosts
  4. ~/.ssh/config

Where does a server look for public keys that may log in as a user?

  1. ~/.ssh/known_hosts
  2. ~/.ssh/config
  3. ~/.ssh/authorized_keys
  4. /etc/passwd

What does scp app.log prod:/tmp/ do?

  1. Downloads app.log from prod
  2. Uploads app.log to /tmp on the host prod
  3. Opens a shell on prod
  4. Deletes /tmp on prod