Sooner or later you will change a file on a machine you can only reach over the network. SSH gives you a shell on that machine, protected by a key pair instead of a password, and a terminal editor (nano for simple edits, vim because it is everywhere) lets you change files there. This lesson follows one safe remote change: a key, a short host alias, a verified host key, a prompt that shows where you are, an edit with a backup, a syntax check, and a second session kept open until the change is proven. Two failures show what goes wrong: a host-key warning ignored, and an SSH change that locks everyone out.
Difficulty: Beginner · Know this first: Lesson 03
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from deciding to make one remote change to having it live and verified. It is a worked example, not a measurement. The connect and validate hops decide whether the change lands on the right machine and leaves you a way back in.
Pick how you log in, what you do with a host-key warning, and what safety net you keep for risky changes.
Three questions. No score is saved anywhere — this is just you against the material.
Remote work grows in four levels: logging in, editing safely, changing services safely, and managing access for a team.
At the basic level you can reach a machine and change a file.
Where it breaks: working on the wrong machine because every prompt looks the same.
Try it: Basic
ssh refuses your key with "UNPROTECTED PRIVATE KEY FILE". Why?
Now do it: Check your key with ls -l ~/.ssh.
At the intermediate level remote work is quick and checked.
Try it: Intermediate
Why add IdentitiesOnly yes to a Host block?
Now do it: Run ssh-add -l.
At the advanced level you never lose access while changing things.
Try it: Advanced
sshd -t passes, but a typo in AllowUsers names a user that does not exist. What catches it?
Now do it: Add a test login to your change checklist.
At the master level access is managed, not collected.
Trade-off: hand edits over SSH are fast for one machine and impossible to repeat or review across a fleet; use them for emergencies, and put the fix into code afterwards.
Try it: Master
An engineer leaves the company. How do you know their access is gone?
Now do it: Count the keys in one server's authorized_keys and who owns each.
An SSH config with a bastion (jump host), so private machines are reached through one hardened entry point:
Host bastion
HostName bastion.example.com
User deploy
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
Host web1
HostName 10.0.4.21 # a private address, reachable only through the bastion
User deploy
ProxyJump bastion
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
A server's host-key fingerprints, for comparing on first connect, are printed on the server with ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub; cloud providers also show them in the instance's console output. Teams can publish them in DNS (SSHFP records) or use SSH host certificates, so clients trust a certificate authority instead of each key.
Recommended server settings, tested with sudo sshd -t and a second session: PasswordAuthentication no, PermitRootLogin no, and AllowGroups (a group is harder to misspell than a list of users and easier to manage).
This is a composite of a failure pattern that keeps repeating; the details are illustrative. Hardening that closed the door.
SSH configuration is now managed in code and rolled out by configuration management, with sshd -t in the pipeline and an automatic test login after each change; AllowGroups replaced AllowUsers; and console access is tested every quarter.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A Linux shell with vim, nano, and the OpenSSH client (sudo apt install -y vim nano openssh-client), and Python 3. No server is needed, and nothing in your own ~/.ssh is touched.
Type each one, read what it prints, and compare it with the note above it.
Edit a file with vim without opening the editor, then check the result. This is how you would script a one-line change.
mkdir -p ~/labs/remote && cd ~/labs/remote printf 'port=8080\nlog=info\n' > app.conf cp -a app.conf app.conf.bak vim -es -c '%s/8080/9090/' -c 'wq' app.conf; echo "vim exit $?" cat app.conf nano --version | head -1
Make a key pair for this lab only, and check its permissions and fingerprint.
ssh-keygen -t ed25519 -N '' -C lab-key -f ~/labs/remote/id_lab -q stat -c '%a %n' id_lab id_lab.pub ssh-keygen -l -f id_lab.pub
Write a lab SSH config with an alias, and ask SSH what it would do, without connecting.
printf 'Host web1\n HostName 203.0.113.10\n User deploy\n Port 2222\n IdentityFile ~/labs/remote/id_lab\n IdentitiesOnly yes\n' > config ssh -F config -G web1 | grep -E '^(hostname|user|port|identityfile|identitiesonly) '
Practise what to do when a host key changes: look the host up in a lab known_hosts file, then remove the old entry, which SSH backs up.
Changes a real system: On a real machine, remove a host key only after confirming why it changed (rebuilt server, reused address) and comparing the new fingerprint with a trusted source.
echo "web1.example.com $(cut -d' ' -f1,2 id_lab.pub)" > known_hosts ssh-keygen -F web1.example.com -f known_hosts | head -1 ssh-keygen -R web1.example.com -f known_hosts ls known_hosts*
Clean up everything the lab made.
cd ~ && rm -rf ~/labs/remote ls ~/labs
ssh_resolve.pyThis program does two things SSH does for you: it resolves a host alias against a config file, where the first value found for each setting wins and wildcard Host blocks apply too, and it checks a server's host key against known_hosts by fingerprint, the way SSH decides whether to warn you. Save it as ssh_resolve.py, then run it.
# ssh_resolve.py
import base64
import fnmatch
import hashlib
CONFIG = """
Host web1
HostName 203.0.113.10
User deploy
Port 2222
Host web*
User ops
IdentityFile ~/.ssh/web_key
Host *
Port 22
ServerAliveInterval 30
"""
def resolve(alias):
seen, block = {}, None
for raw in CONFIG.strip().splitlines():
key, _, value = raw.strip().partition(" ")
if key == "Host":
block = any(fnmatch.fnmatch(alias, p) for p in value.split())
elif block and key.lower() not in seen: # first value wins
seen[key.lower()] = value.strip()
seen.setdefault("hostname", alias)
return seen
for alias in ("web1", "web2", "db1"):
print(alias, "->", resolve(alias))
print()
def fingerprint(blob_b64): # OpenSSH style: SHA256, base64, no padding
return "SHA256:" + base64.b64encode(hashlib.sha256(base64.b64decode(blob_b64)).digest()).decode().rstrip("=")
known = {"web1.example.com": base64.b64encode(b"web1 host key, 2025 build").decode()}
for host, presented in (("web1.example.com", base64.b64encode(b"web1 host key, 2025 build").decode()),
("web1.example.com", base64.b64encode(b"a different machine's key").decode()),
("new.example.com", base64.b64encode(b"new host key").decode())):
if host not in known:
verdict = "unknown host: compare " + fingerprint(presented)[:20] + "... with a trusted source"
elif known[host] == presented:
verdict = "key matches: connect"
else:
verdict = "CHANGED: was " + fingerprint(known[host])[:20] + "..., now " + fingerprint(presented)[:20] + "...: stop and check"
print(f"{host:<17} {verdict}")
Run it, and you should see this output:
$ python3 ssh_resolve.py
web1 -> {'hostname': '203.0.113.10', 'user': 'deploy', 'port': '2222', 'identityfile': '~/.ssh/web_key', 'serveraliveinterval': '30'}
web2 -> {'user': 'ops', 'identityfile': '~/.ssh/web_key', 'port': '22', 'serveraliveinterval': '30', 'hostname': 'web2'}
db1 -> {'port': '22', 'serveraliveinterval': '30', 'hostname': 'db1'}
web1.example.com key matches: connect
web1.example.com CHANGED: was SHA256:lsYTgCpIQTrFZ..., now SHA256:Uy8UyTSzC2wZT...: stop and check
new.example.com unknown host: compare SHA256:Ce2QXguOYxRkA... with a trusted source
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/editing-files-and-remote-hosts-nano-vim-and-ssh-safely && cd ~/labs/editing-files-and-remote-hosts-nano-vim-and-ssh-safely) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Editing Files and Working on Remote Hosts: nano, vim, and SSH Without Locking Yourself Out", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Edit a file with vim without opening the editor, then check the result. This is how you would script a one-line change.'
'Make a key pair for this lab only, and check its permissions and fingerprint.'
'Write a lab SSH config with an alias, and ask SSH what it would do, without connecting.'
'Practise what to do when a host key changes: look the host up in a lab known_hosts file, then remove the old entry, which SSH backs up.'
'Clean up everything the lab made.'
)
step_1() {
mkdir -p ~/labs/remote && cd ~/labs/remote
printf 'port=8080\nlog=info\n' > app.conf
cp -a app.conf app.conf.bak
vim -es -c '%s/8080/9090/' -c 'wq' app.conf; echo "vim exit $?"
cat app.conf
nano --version | head -1
}
step_2() {
ssh-keygen -t ed25519 -N '' -C lab-key -f ~/labs/remote/id_lab -q
stat -c '%a %n' id_lab id_lab.pub
ssh-keygen -l -f id_lab.pub
}
step_3() {
printf 'Host web1\n HostName 203.0.113.10\n User deploy\n Port 2222\n IdentityFile ~/labs/remote/id_lab\n IdentitiesOnly yes\n' > config
ssh -F config -G web1 | grep -E '^(hostname|user|port|identityfile|identitiesonly) '
}
step_4() {
echo "web1.example.com $(cut -d' ' -f1,2 id_lab.pub)" > known_hosts
ssh-keygen -F web1.example.com -f known_hosts | head -1
ssh-keygen -R web1.example.com -f known_hosts
ls known_hosts*
}
step_5() {
cd ~ && rm -rf ~/labs/remote
ls ~/labs
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, cut, head, ssh, mkdir, rm, cp, cat, Pipes, Redirection, If...Else, Exit codes.Your team of eight manages 40 Linux servers over SSH, with shared passwords and hand edits. Design a safer way of working.
How do people authenticate? How are host keys trusted? How are servers named and reached? How are changes made, tested, and recorded? How is access removed? What is the recovery path if SSH breaks?
Say 40 servers, 8 engineers, 2 of whom join or leave each year, and about 30 changes a month.
Personal Ed25519 keys (or SSH certificates from an identity provider); password logins and root logins off; a bastion with ProxyJump and audit logs; published host-key fingerprints or host certificates; config aliases in a shared repository; changes through configuration management with config tests and a test login; a tested console path; access removed centrally when someone leaves.
A bastion and certificates add setup and a dependency on the identity system; per-person keys on every server are simpler to start and hard to keep accurate.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Host key warning ignored | Hop 4: Connect | Breaks | "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!" The engineer runs ssh-keygen -R web1 and accepts the new key at the prompt. Production had moved to a new address the week before; 203.0.113.10 now belongs to a rebuilt test server. |
| Host key warning ignored | Hop 5: Where am I | Breaks | The prompt says deploy@test-07, which nobody reads. The fix is applied, nginx reloads, and production keeps failing. Fifty minutes later someone notices the host name in the terminal history. |
| Locked out by an SSH change | Hop 7: Validate | Breaks | No sshd -t. The typo in AllowUsers (adminn) is valid syntax, so even sshd -t would not have caught it; only a test login would. |
| Locked out by an SSH change | Hop 8: Apply safely | Breaks | sshd is restarted and the only session is closed straight away. New logins fail with "Permission denied (publickey)". Recovery means the cloud provider's serial console, a password reset, and fixing the file: 40 minutes. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.