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.
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_keyson 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:
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 shareThe -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 keysWhat 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.
A TCP connection opens. Both sides agree on encryption, so everything after this is private.
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.
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.gitThe 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 truePut the steps for setting up SSH access to GitHub on a new laptop in order.
- Tap the steps below in the right order.
~/.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:
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.
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 '
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 grepQuote 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 firstrsync 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/putsindex.htmlin/srv/app/.rsync -a dist server:/srv/app/creates/srv/app/dist/. --deleteremoves 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-runfirst.
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 appdbRead -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 opens port 5433 on your laptop and waits.
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 backgroundtmux 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.pubThe 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 each task to the tool or file.
- 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:portcarries 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.