Platform Engineering · Lesson 04

Editing Files and Working on Remote Hosts: nano, vim, and SSH Without Locking Yourself Out

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: how does your remote change go?

Pick how you log in, what you do with a host-key warning, and what safety net you keep for risky changes.

14minutes
rightmachine changed
yesway back in

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Remote work grows in four levels: logging in, editing safely, changing services safely, and managing access for a team.

Basic — Log in and edit

At the basic level you can reach a machine and change a file.

  • An Ed25519 key pair and ssh-copy-id.
  • nano for quick edits; vim's i, Esc, :wq, and :q!.
  • hostname and whoami before you change anything.

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.

Intermediate — Work efficiently and safely

At the intermediate level remote work is quick and checked.

  • Host aliases in ~/.ssh/config, checked with ssh -G.
  • Host-key fingerprints verified; known_hosts kept clean with ssh-keygen -R after a confirmed rebuild.
  • tmux for long-running work.

Try it: Intermediate

Why add IdentitiesOnly yes to a Host block?

Now do it: Run ssh-add -l.

Advanced — Change services without outages

At the advanced level you never lose access while changing things.

  • Config tests (nginx -t, sshd -t, visudo -c) before every reload.
  • A second session for SSH, firewall, and network changes.
  • Out-of-band or console access known and tested.

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.

Master — Access for a team

At the master level access is managed, not collected.

  • SSH certificates or a bastion with single sign-on, short-lived access, and audit logs.
  • Keys removed automatically when people leave; no shared accounts.
  • Changes made through configuration management, not by hand on servers.

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.

Go deeper

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).

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. Hardening that closed the door.

Timeline

  • 16:02To pass an audit finding, an engineer turns off password logins and adds an AllowUsers line on a database server, then restarts sshd and logs out.
  • 16:20The on-call engineer cannot log in: "Permission denied (publickey)". The AllowUsers line lists a misspelt admin account, and the deploy user's key is on a laptop that is away for repair.
  • 16:55Access is restored through the provider's serial console and the line is fixed.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Edit a file with vim without opening the editor, then check the result. This is how you would script a one-line change.

    Reversible

    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

    Options: cp -a copies with permissions and times (your backup); vim -es runs vim silently in Ex mode; -c '%s/8080/9090/' replaces on every line, -c 'wq' writes and quits.

    Expect: vim exit 0, then port=9090 and log=info; nano prints its version, such as GNU nano, version 8.x. To practise interactively: vim app.conf, press i, type, Esc, then :wq; or nano app.conf, Ctrl+O, Enter, Ctrl+X.

    Clean up: cd ~ && rm -rf ~/labs/remote (the last step).

  2. Make a key pair for this lab only, and check its permissions and fingerprint.

    Reversible

    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

    Options: -t ed25519 key type; -N '' an empty passphrase (only acceptable for a throwaway lab key; use a passphrase for real keys); -C a comment; -f the file; -q quiet. stat -c '%a %n' prints the permission bits and name (on macOS: stat -f '%Lp %N').

    Expect: 600 id_lab (only you can read the private key) and 644 id_lab.pub; then 256 SHA256:…random… lab-key (ED25519). Your fingerprint differs, because every key is new.

    If it fails: If a real key ever has wider permissions, SSH refuses it with "UNPROTECTED PRIVATE KEY FILE"; fix with chmod 600.

  3. Write a lab SSH config with an alias, and ask SSH what it would do, without connecting.

    Read-only

    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) '

    Options: -F config uses this file instead of ~/.ssh/config; -G prints the final settings and exits without connecting. 203.0.113.10 is an address reserved for documentation.

    Expect: Five lines (order may vary): user deploy, hostname 203.0.113.10, port 2222, identitiesonly yes, identityfile ~/labs/remote/id_lab.

  4. 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.

    Reversible

    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*

    Options: ssh-keygen -F host -f file finds a host's entry; -R host removes it. Without -f both act on your real ~/.ssh/known_hosts.

    Expect: # Host web1.example.com found: line 1; then the removal prints the same line, known_hosts updated. and Original contents retained as known_hosts.old; ls shows both files.

  5. Clean up everything the lab made.

    Potentially destructive

    cd ~ && rm -rf ~/labs/remote
    ls ~/labs

    Expect: No error; remote is no longer listed. Your own ~/.ssh was never used.

2. Python: ssh_resolve.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your team of eight manages 40 Linux servers over SSH, with shared passwords and hand edits. Design a safer way of working.

Clarifying questions to ask

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?

Rough sizing

Say 40 servers, 8 engineers, 2 of whom join or leave each year, and about 30 changes a month.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Host key warning ignoredHop 4: ConnectBreaks"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 ignoredHop 5: Where am IBreaksThe 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 changeHop 7: ValidateBreaksNo 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 changeHop 8: Apply safelyBreakssshd 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.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Key pair → Public key → Config alias → Connect → Where am I → Edit → Validate → Apply safely → Leave. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 05
Git and GitHub Setup: Identity, SSH Keys, .gitignore, and Your First Pull Request

Git records every change to your files as a commit with an author, a message, and a hash; GitHub (or GitLab, or Bitbucket) hosts a shared copy that a team reviews and merges into.

Go to Lesson 05 →

Or browse the full course from the Lessons index.