SSH and remote access
SSH (Secure Shell) is how you work on remote servers: an encrypted terminal session to any machine in the world. It also copies files, forwards ports, and is what Git, Ansible and many deployment tools use underneath. Setting it up well (keys, config, a locked-down server) is one of the first things every developer learns.
💡 In this lesson the "remote server" is the same machine (
localhost) with an SSH server running, so the examples could run for real. Replacelocalhostwith your server's IP or name.
Connecting
ssh user@host # e.g. ssh deploy@203.0.113.10
ssh -p 2222 user@host # a non-standard port
ssh user@host 'uptime' # run one command and come backThe first time you connect to a server, SSH shows its fingerprint and asks whether you trust it:
The authenticity of host '203.0.113.10' can't be established.
ED25519 key fingerprint is SHA256:Uq3yQ0b2…
Are you sure you want to continue connecting (yes/no/[fingerprint])?Answering yes saves the server's key in ~/.ssh/known_hosts. From then on, SSH checks it on every connection and refuses if it changes ("REMOTE HOST IDENTIFICATION HAS CHANGED"), which protects you from someone impersonating the server. If you rebuilt the server yourself, remove the old entry with ssh-keygen -R host.
Key-based login
Passwords can be guessed, and bots try millions of them against every server on the internet. SSH keys are far safer: a private key that never leaves your computer, and a public key you put on each server.
1. Create a key pair (once, on your computer)
ssh-keygen -t ed25519 -C "you@laptop" -f ~/.ssh/id_ed25519 -N "" -q
ls -l ~/.ssh/ | awk 'NR > 1 { print $1, $NF }'
cut -c1-40 ~/.ssh/id_ed25519.pub-rw------- id_ed25519 -rw-r--r-- id_ed25519.pub ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMCm
ed25519is the modern, recommended key type. (-t rsa -b 4096if a very old server requires RSA.)- The private key is
600: only you can read it. SSH refuses keys with looser permissions. -N ""means no passphrase, used here so the example can run unattended. On your laptop, set a passphrase: then a stolen key file is useless.ssh-agent(built into macOS and most desktops) remembers it so you type it once per session.
2. Put the public key on the server
sudo systemctl start ssh
mkdir -p ~/.ssh && chmod 700 ~/.ssh
cat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
ssh -o StrictHostKeyChecking=accept-new you@localhost 'echo "logged in to $(hostname) as $(whoami) without a password"' 2>&1Warning: Permanently added 'localhost' (ED25519) to the list of known hosts. logged in to devbox as you without a password
From your own computer, ssh-copy-id user@server does the copying for you (asking for the password one last time). Cloud providers let you add the public key when creating the server, so you never need a password at all.
StrictHostKeyChecking=accept-new accepted the new host key automatically and printed the warning above. Don't make that a habit for servers you don't control: checking the fingerprint is the point.
Running remote commands
ssh you@localhost 'uname -sr; df -h / | tail -1 | awk "{ print \$5 \" of / used\" }"'
ssh you@localhost 'cat /etc/os-release' | grep PRETTY
echo "line from my laptop" | ssh you@localhost 'cat > from-ssh.txt'
ssh you@localhost 'cat from-ssh.txt'Linux 6.12.54-linuxkit 7% of / used PRETTY_NAME="Ubuntu 24.04.5 LTS" line from my laptop
Output comes back to your terminal, and pipes work in both directions: that's how backups like pg_dump | ssh backup-server 'cat > db.sql' stream across the network without temporary files.
Copying files: scp and rsync
mkdir -p project && echo "v1" > project/app.txt && echo "x" > project/debug.log
scp -q project/app.txt you@localhost:/tmp/app.txt
ssh you@localhost 'cat /tmp/app.txt'
rsync -az --exclude '*.log' project/ you@localhost:/tmp/deploy/
ssh you@localhost 'ls /tmp/deploy'
echo "version 2" > project/app.txt
rsync -az --itemize-changes project/ you@localhost:/tmp/deploy/ --exclude '*.log'v1 app.txt <f.st...... app.txt
| Tool | Best for |
|---|---|
scp file host:path |
Copying a file or two (-r for folders) |
rsync -az src/ host:dest/ |
Folders, repeated syncs: only changed files are sent, and it can resume |
rsync --delete |
Also delete files on the destination that no longer exist in the source (a mirror). Try with --dry-run first |
sftp host |
Interactive file browsing |
⚠️ With
rsync, the trailing slash matters:project/copies the contents of project;projectcopies the folder itself into the destination.
The SSH config file
Typing ssh -i ~/.ssh/work_key -p 2222 deploy@203.0.113.10 every time gets old. Put it in ~/.ssh/config instead:
Host shop
HostName localhost
User you
Port 22
IdentityFile ~/.ssh/id_ed25519
Host *
ServerAliveInterval 60
AddKeysToAgent yeschmod 600 ~/.ssh/config
ssh shop 'echo "connected via the alias, as $USER"'
scp -q shop:/tmp/app.txt copied.txt && cat copied.txtconnected via the alias, as you v1
Now ssh shop, scp shop:… and rsync … shop:… all use those settings. ServerAliveInterval stops idle connections from being dropped. A ProxyJump bastion line connects through a jump host, the usual way to reach servers in a private network.
Port forwarding: tunnels
SSH can carry other connections through its encrypted tunnel. The most useful one is a local forward: reach a port on the server as if it were on your laptop, without opening it to the internet. Perfect for a database or an admin page that only listens on 127.0.0.1:
sudo systemctl start nginx
ssh -f -N -L 8081:localhost:80 shop # laptop port 8081 → server port 80
curl -s http://localhost:8081/ | grep -o "<title>.*</title>"
pkill -f "8081:localhost:80"<title>Welcome to nginx!</title>
| Option | Direction | Example |
|---|---|---|
-L 5433:localhost:5432 |
Your port → a port reachable from the server | Use pgAdmin on your laptop with the server's PostgreSQL |
-R 8080:localhost:3000 |
A server port → your machine | Show a local dev server to someone |
-D 1080 |
A SOCKS proxy through the server | Browse as if you were in the server's network |
-N / -f |
Don't run a command / go to the background |
Securing the SSH server
The server's settings are in /etc/ssh/sshd_config (and files in /etc/ssh/sshd_config.d/). On any internet-facing server, turn off password logins and root logins once your key works:
cat > /etc/ssh/sshd_config.d/50-hardening.conf <<'EOF'
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
EOF
sshd -t && echo "config OK"
systemctl reload ssh
sshd -T | grep -E "^(passwordauthentication|permitrootlogin|pubkeyauthentication) "config OK permitrootlogin no pubkeyauthentication yes passwordauthentication no
sshd -ttests the config. Always run it before reloading: a broken config can stop SSH from starting.- Keep your current session open while you test a new login in a second terminal. If something's wrong, you can still fix it.
- Add fail2ban (
sudo apt install fail2ban) to ban IPs that keep failing to log in, and watch logins withjournalctl -u ssh.
Practice
- Create an ed25519 key with a passphrase and look at the two files it made.
- Add a
Hostentry to~/.ssh/configfor a server you use (orlocalhost) and connect with the alias. - Sync a folder to a server with
rsync, change one file, and sync again with--itemize-changesto see that only that file is sent. - Open a tunnel with
-Lto reach a service that only listens on the server's127.0.0.1.
1.Which key do you copy to the server?
2.SSH warns "REMOTE HOST IDENTIFICATION HAS CHANGED". What does it mean?
3.What does ssh -L 5433:localhost:5432 db-server do?
4.Which settings should an internet-facing server have?