Skip to content

Lesson 11 of 18Your tools

SSH and Remote Machines

Log in to servers and GitHub with SSH keys, set up ~/.ssh/config, copy files with rsync, tunnel to private databases, and keep keys safe.

21 min read0/5 questions

On your first week you will get a message like: "Your access is set up. The staging box is 10.0.4.17, user deploy, and the database is only reachable from inside the VPC." Or simply: "Add your SSH key to GitHub so you can clone the repo." Both assume you know SSH, the protocol behind almost every remote login, every git push over git@github.com, and every quick look at a production server. Knowing it well means you can debug "Permission denied (publickey)" without asking for help, reach a private database safely, and not be the person whose leaked key forces a security incident.

Keys, not passwords

SSH uses public-key cryptography. You generate a key pair: two files that belong together.

  • The private key (~/.ssh/id_ed25519) stays on your laptop. Never copy it, email it, paste it into Slack or commit it.
  • The public key (~/.ssh/id_ed25519.pub) is safe to share. You give it to GitHub, or append it to ~/.ssh/authorized_keys on a server.

When you connect, the server sends a random challenge. Your SSH client signs it with the private key, and the server checks the signature with the public key it has on file. The private key never crosses the network, so there is nothing for an eavesdropper or a compromised server to steal and reuse. The idea fits in a few lines:

Python
import hashlibimport secrets # A toy key pair with tiny numbers so you can see the math.# Real SSH keys (Ed25519) use different math, but the idea is the same:# only the private key can sign, and anyone with the public key can check.n = 61 * 53 # 3233, part of both keyspublic_e = 17 # public key: (n, 17) -> goes on the serverprivate_d = 2753 # private key: (n, 2753) -> never leaves your laptop def digest(message: bytes) -> int: return int.from_bytes(hashlib.sha256(message).digest(), "big") % n def sign(message: bytes) -> int: # needs the PRIVATE key return pow(digest(message), private_d, n) def verify(message: bytes, signature: int) -> bool: # needs only the PUBLIC key return pow(signature, public_e, n) == digest(message) challenge = secrets.token_bytes(16) # server: "prove it, sign this"signature = sign(challenge) # your laptop signs itprint("signature valid:", verify(challenge, signature)) forged = (signature + 1) % n # an attacker without the private keyprint("forged valid: ", verify(challenge, forged)) # A fresh challenge every login means an old signature is useless.# (With numbers this tiny, a 1 in 3233 fluke is possible. Real keys make it impossible in practice.)print("replay valid: ", verify(secrets.token_bytes(16), signature))
Output
Press Run (⌘ Enter) to see what happens.

Create your key with Ed25519, the current default recommendation. Use RSA (3072 bits or more) only if an old system cannot handle Ed25519.

ssh-keygen -t ed25519 -C "you@example.com"# Enter file: press Enter for the default, ~/.ssh/id_ed25519# Enter passphrase: use one; the agent below means you rarely type itcat ~/.ssh/id_ed25519.pub     # this line is what you share

The -C comment is just a label so you can tell keys apart later. A passphrase encrypts the private key file, so a stolen laptop backup is not an instant login. To avoid typing it all day, load the key into ssh-agent, a background process that holds unlocked keys in memory:

# macOS: store the passphrase in Keychain so it survives rebootsssh-add --apple-use-keychain ~/.ssh/id_ed25519# Linux: the agent usually runs already with your desktop sessionssh-add ~/.ssh/id_ed25519ssh-add -l     # list loaded keys
Quick check
A teammate asks for your SSH key so they can give you access to the staging server. What do you send?
Need a nudge? A hint rules out a wrong answer.

What happens when you connect

The very first time you connect to a server, SSH asks you to confirm the server's identity:

The authenticity of host 'staging (203.0.113.10)' can't be established.
ED25519 key fingerprint is SHA256:4NniThqC3Y73FBWX+ojIrG7A0V9om9LsFbLkoQS/d4c.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

Authentication goes in both directions. You prove who you are with your key, but first the server proves who it is with its host key. When you type yes, your client saves that host key in ~/.ssh/known_hosts. Every later connection checks it.

An SSH login, both directions
Your laptopServerconnect to port 22host key + signatureI am deploy, key Xsign this challengesignaturewelcome, shell starts

A TCP connection opens. Both sides agree on encryption, so everything after this is private.

1/6

That stored host key is what protects you from a man-in-the-middle attack, where someone on the network pretends to be the server. If the key ever changes, SSH stops with a large WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! banner and refuses to connect.

Quick check
You SSH into a production server you use every day and get REMOTE HOST IDENTIFICATION HAS CHANGED. Nobody announced maintenance. What is the right first move?
Need a nudge? A hint rules out a wrong answer.

SSH and GitHub

To push and pull without tokens, add your public key in GitHub under Settings, SSH and GPG keys, New SSH key, then test it:

ssh -T git@github.com# Hi your-username! You've successfully authenticated, but GitHub does not provide shell access.

That message, even with its non-zero exit code, means it worked. A remote URL decides whether Git uses SSH or HTTPS. git@github.com:acme/app.git is SSH and uses your key. https://github.com/acme/app.git is HTTPS and uses a token or a credential manager. Both are fine. SSH is convenient once set up, and HTTPS gets through corporate firewalls that block port 22. Switch an existing clone with:

git remote -vgit remote set-url origin git@github.com:acme/app.git

The same key can also sign your commits, which puts a "Verified" badge on them in GitHub. Many companies require it. It needs Git 2.34 or later, and you add the key a second time in GitHub with the key type set to Signing key:

git config --global gpg.format sshgit config --global user.signingkey ~/.ssh/id_ed25519.pubgit config --global commit.gpgsign true
Put it in order5 steps

Put the steps for setting up SSH access to GitHub on a new laptop in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

~/.ssh/config: stop typing IPs

Typing ssh -i ~/.ssh/id_ed25519 -p 2222 deploy@203.0.113.10 gets old fast. Put the details in ~/.ssh/config once, and every SSH-based tool (ssh, scp, rsync, Git, VS Code Remote) uses them:

~/.ssh/config
Host staging  HostName 203.0.113.10  User deploy  Port 2222  IdentityFile ~/.ssh/id_ed25519Host db-tunnel  HostName bastion.example.com  User ada  LocalForward 5433 db.internal:5432# Defaults for every host go LASTHost *  AddKeysToAgent yes  IdentitiesOnly yes  UseKeychain yes          # macOS only; on Linux remove it or add "IgnoreUnknown UseKeychain"

Now ssh staging is enough. The ordering rule trips up everyone once: for each setting, SSH uses the first value it finds, reading top to bottom. A Host * block at the top wins over anything more specific below it, so defaults go at the end. When a connection does something you did not expect, ssh -G staging prints the final settings SSH will actually use, and ssh -v staging shows each step of the connection, including which keys it tried.

Predict the outputShell

With this ~/.ssh/config, what does the last command print?

# ~/.ssh/config
Host *
User root

Host staging
HostName 203.0.113.10
User deploy

$ ssh -G staging | grep '^user '
Need a nudge? Hints walk you through it.

Running commands and copying files

You do not always need an interactive shell. Put the command after the host:

ssh staging 'df -h /; uptime'                 # run, print, disconnectssh staging 'tail -n 200 /var/log/app.log' | grep ERROR   # remote output, local grep

Quote the remote command. Without quotes, parts of it (like ; or |) are interpreted by your local shell first.

To copy files, scp works like cp with a host: prefix. Since OpenSSH 9.0 it uses the SFTP protocol underneath, but you use it the same way:

scp app.tar.gz staging:/tmp/          # uploadscp staging:/var/log/app.log .        # downloadrsync -avz --delete dist/ staging:/srv/app/   # sync a folder: only changes are sentrsync -avz --dry-run --delete dist/ staging:/srv/app/   # preview first

rsync wins for anything you copy more than once. It compares both sides and transfers only what changed, it can resume, and --delete makes the destination an exact mirror. -a (archive) keeps permissions and timestamps and recurses, -v lists files, and -z compresses in transit. Recent macOS ships openrsync, a compatible reimplementation that handles all the flags here. Two details matter:

  • A trailing slash on the source means "the contents of". rsync -a dist/ server:/srv/app/ puts index.html in /srv/app/. rsync -a dist server:/srv/app/ creates /srv/app/dist/.
  • --delete removes files on the destination that are not in the source. With the wrong path, that is a fast way to wipe a server. Run it with --dry-run first.

Tunnels: reaching a private database

Production databases should not be on the public internet. They sit in a private network, and you reach them through a server that is reachable, often called a bastion or jump host. SSH local port forwarding makes a port on your laptop lead to that database:

ssh -N -L 5433:db.internal:5432 ada@bastion.example.com# in another terminal:psql -h localhost -p 5433 -U app appdb

Read -L 5433:db.internal:5432 as "local port 5433 goes to db.internal, port 5432, as seen from the server". -N means "no remote command, just forward". If the database runs on the server itself, the target is localhost:5432, and localhost there means the server, not your laptop. Port 5433 is used locally so it does not clash with a Postgres you may already run on 5432.

ssh -L 5433:db.internal:5432 bastion
psql: localhost:5433psqllocalhost:5433ssh client: listens on 5433ssh clientlistens on 5433bastion: public, port 22bastionpublic, port 22db.internal: private, 5432db.internalprivate, 5432plain TCP, on your laptopencrypted SSHinside the VPC

ssh -L opens port 5433 on your laptop and waits.

1/4

If the server you want is behind the bastion, use ProxyJump instead of logging in twice: ssh -J ada@bastion.example.com deploy@10.0.4.17, or ProxyJump bastion in ~/.ssh/config. Prefer it over agent forwarding (ssh -A), which lets anyone with root on the intermediate server use your loaded keys for as long as you are connected.

Staying alive on a server

Close your laptop and your SSH session ends, and so does anything running in it: that 40-minute migration or data backfill dies halfway. Two fixes:

tmux new -s backfill        # start a named session on the serverpython3 backfill.py         # run the long job inside it# press Ctrl+B, then D, to detach. The job keeps running. Log out freely.tmux ls                     # later: list sessionstmux attach -t backfill     # reattach and see the outputnohup ./backfill.sh > backfill.log 2>&1 &   # no tmux: ignore hangups, run in background

tmux is the better habit: you can reattach, scroll back and see progress. nohup only makes the process ignore the hangup signal sent when you disconnect, and you read its output from the log file. For anything that must run regularly or survive reboots, neither is right. That is a job for a scheduler or a service manager such as systemd.

Keeping keys safe

SSH is strict about file permissions and will ignore a private key that others can read, printing WARNING: UNPROTECTED PRIVATE KEY FILE!. The correct modes:

chmod 700 ~/.sshchmod 600 ~/.ssh/id_ed25519 ~/.ssh/config ~/.ssh/authorized_keyschmod 644 ~/.ssh/id_ed25519.pub

The habits that matter:

  • One key per device. If a laptop is lost or stolen, delete that one public key from GitHub and from every server's authorized_keys. Nothing else needs to change. Shared keys mean rotating everything.
  • Never commit private keys, and never paste them into a chat or a ticket. Secret scanners catch them in public repos within minutes, and attackers scan just as fast.
  • Always use a passphrase. With ssh-agent and Keychain, it costs you almost nothing.
  • Do not disable host key checking to make a warning go away. That check is the only thing standing between you and a man-in-the-middle.
Match the pairs0/6 matched

Match each task to the tool or file.

Choose an item, then its match on the other side.
Key terms
key pair
A private key that signs and stays on your machine, plus a public key that verifies and can be shared.
Ed25519
The modern default SSH key type: small, fast and secure. Use RSA (3072+ bits) only for legacy systems.
ssh-agent
A background process that holds unlocked private keys so you type the passphrase once.
known_hosts
Your record of each server's host key. A mismatch triggers the host key changed warning.
authorized_keys
The file on a server listing the public keys allowed to log in as that user.
port forwarding
ssh -L local:target:port carries a local port through SSH to a host reachable from the server.
bastion
A hardened server exposed to the internet that you hop through to reach private machines.