By the end you'll know
- What "joiners, movers and leavers" means, and why leavers are where security slips
- How to give someone a login with an SSH key and no password
- Why locking a password doesn't stop someone logging in
- Everything that has to go when someone leaves, and how to prove it's gone
- How to keep a server matching a list of staff, without one bad list removing everyone
Before you start
- You need: Vagrant and VMware Fusion or VirtualBox, as in Linux Lesson 7, and the practice folder:
git clone https://github.com/Kwamib/automation-practice.git, orgit pullin it. - This lesson uses users, groups and permissions from Linux Lesson 5, and SSH keys from Linux Lesson 11.
- Where commands run: on your own computer to build the server, then on the server, called
office. - The output below is from a real run on November 18, 2026, at about 11am in New York (16:00 UTC).
The problem: people leave, access stays
Every organization has the same three moments for each person, often called joiners, movers and leavers:
- A joiner needs access on day one.
- A mover changes team, and needs some access added and some taken away.
- A leaver needs every bit of access removed, on their last day.
Joiners get done, because someone is waiting to start work. Leavers are where it slips, because nobody is waiting. Access that outlives someone's job is a favorite finding of security audits, and a real risk: a former employee, or anyone who has their laptop, can still get in.
The hard part isn't one command. It's that "access" is several separate things, and a quick offboarding removes one of them. This lesson shows what gets missed, then builds a script that removes all of it, and can prove it.
The server
On your own computer:
cd ~/Apps/automation-practice/users
vagrant up
vagrant ssh
cd .../users: Vagrant uses theVagrantfilein this folder, which builds a server calledoffice.vagrant up: builds it and runssetup.sh, which makes the groups, installs thestaffscript, and makes SSH keys for three new starters.vagrant ssh: logs you in, as the admin,vagrant.
(On the server)
sudo staff audit
ls ~/keys
cat ~/roster.csv
NAME GROUPS KEYS CRON PROCS STATUS
alice alice.pub bob bob.pub carol carol.pub
name,groups,key
alice,developers,/home/vagrant/keys/alice.pub
carol,deployers,/home/vagrant/keys/carol.pub
sudo staff audit: who has access. Nobody yet, so just the column names.sudoruns it as root, because only root can see and change everyone's accounts.ls ~/keys: the keyssetup.shmade.~is your home folder. Each person has a private key (no ending) and a public key (.pub).cat ~/roster.csv: a list of who should have access, used later.
In real life, each person makes their own key pair on their own computer, keeps the private key, and sends you only the public one. The private key never leaves their computer, and you never see it. The lab keeps all three here so you can log in as each person to test.
There are two access groups, each giving different access, plus one group that marks everyone the script looks after:
| Group | For |
|---|---|
developers | People who work on the bookshop's code |
deployers | People who release it |
bookshop-staff | Everyone the script manages. It only ever touches people in this group: never system accounts, and never the admin's own login. |
Access goes through groups, not to people one at a time. Give a group a permission once, then add or remove people from the group. A mover changes groups; nothing else needs touching.
The script
staff, installed at /usr/local/sbin/staff, where sbin is for admin tools. Also on GitHub (opens in a new tab):
#!/usr/bin/env bash
# staff: give people logins on this server, take them away completely, and
# show who has access. Only touches people in the "bookshop-staff" group,
# never system accounts or the admin's own login.
#
# staff audit who has access, and how
# staff add NAME GROUPS KEYFILE give NAME a login (GROUPS: developers,deployers)
# staff remove NAME take NAME's access away, completely
# staff sync ROSTER make the server match a roster file
#
# add, remove and sync are dry runs unless you add --apply at the end.
# Exit codes: 0 done, 1 something failed, 2 called wrongly or refused.
set -euo pipefail
ARCHIVE=${ARCHIVE:-/var/backups/staff}
LOG=${LOG:-/var/log/staff.log}
MAX_REMOVALS=${MAX_REMOVALS:-1}
ACCESS_GROUPS="developers deployers"
who_ran=${SUDO_USER:-$(id -un)}
apply=0
args=()
for a in "$@"; do
if [ "$a" = --apply ]; then apply=1; else args+=("$a"); fi
done
set -- "${args[@]}"
say() { printf '%s staff: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
refuse() { say "refusing: $*"; exit 2; }
usage() { sed -n '6,11p' "$0" | sed -E 's/^# ?//' >&2; exit 2; }
# Record a change in the log, with who made it. Only real changes are recorded.
record() {
if [ "$apply" -eq 0 ]; then say "(dry run) $*"; return 0; fi
say "$*"
printf '%s %s: %s\n' "$(date -u +%FT%TZ)" "$who_ran" "$*" >>"$LOG"
}
# run CMD...: run it, or in a dry run, show it.
run() {
if [ "$apply" -eq 1 ]; then "$@"; else say "would run: $*"; fi
}
[ "$(id -u)" -eq 0 ] || { say "run me with sudo"; exit 2; }
valid_name() { [[ $1 =~ ^[a-z][a-z0-9-]{1,30}$ ]]; }
is_staff() { id -nG "$1" 2>/dev/null | tr ' ' '\n' | grep -qx bookshop-staff; }
is_expired() {
local exp today
exp=$(getent shadow "$1" | cut -d: -f8)
today=$(( $(date +%s) / 86400 ))
[ -n "$exp" ] && [ "$exp" -le "$today" ]
}
staff_members() { getent group bookshop-staff | cut -d: -f4 | tr ',' '\n' | grep -v '^$' || true; }
cmd_add() {
[ $# -eq 3 ] || usage
local name=$1 groups=$2 key=$3 g
valid_name "$name" || refuse "'$name' isn't a valid login name (lowercase letters, digits and -)"
for g in ${groups//,/ }; do
[[ " $ACCESS_GROUPS " == *" $g "* ]] || refuse "'$g' isn't one of: $ACCESS_GROUPS"
done
[ -r "$key" ] || refuse "can't read the key file $key"
local fp verb=added
fp=$(ssh-keygen -l -f "$key" 2>/dev/null) || refuse "$key isn't an SSH public key"
if id "$name" >/dev/null 2>&1; then
is_staff "$name" || refuse "$name exists but isn't in the bookshop-staff group: not one of ours"
is_expired "$name" && refuse "$name was removed; to give them access again, ask an admin to review it first"
say "$name already exists: making sure their groups and key are right"
verb=checked
run usermod -G "bookshop-staff,$groups" "$name"
else
run useradd --create-home --shell /bin/bash --groups "bookshop-staff,$groups" "$name"
run usermod --lock "$name"
fi
run install -d -m 700 -o "$name" -g "$name" "/home/$name/.ssh"
run install -m 600 -o "$name" -g "$name" "$key" "/home/$name/.ssh/authorized_keys"
record "$verb $name (groups: $groups; key: ${fp%% (*})"
}
cmd_remove() {
[ $# -eq 1 ] || usage
local name=$1 g
valid_name "$name" || refuse "'$name' isn't a valid login name"
id "$name" >/dev/null 2>&1 || refuse "there's no user called $name"
is_staff "$name" || refuse "$name isn't in the bookshop-staff group: not one of ours"
is_expired "$name" && { say "$name was already removed"; return 0; }
# 1. No more logins, by any route: lock the password and expire the account.
run usermod --lock --expiredate 1 "$name"
# 2. Remove their SSH keys, so nothing can log in as them.
run rm -f "/home/$name/.ssh/authorized_keys"
# 3. Remove scheduled jobs they set up.
if crontab -l -u "$name" >/dev/null 2>&1; then run crontab -r -u "$name"; fi
# 4. Stop anything still running as them.
if pgrep -u "$name" >/dev/null; then
say "$name has $(pgrep -u "$name" | wc -l) processes running"
run pkill -KILL -u "$name"
if [ "$apply" -eq 1 ]; then
sleep 1
! pgrep -u "$name" >/dev/null || say "WARNING: $name still has processes running; check with: ps -u $name"
fi
fi
# 5. Take them out of every access group.
for g in $ACCESS_GROUPS; do
if id -nG "$name" | tr ' ' '\n' | grep -qx "$g"; then run gpasswd -d "$name" "$g" >/dev/null; fi
done
# 6. Keep a copy of their home folder, readable by root only.
run install -d -m 700 "$ARCHIVE"
run tar -czf "$ARCHIVE/$name-$(date -u +%Y%m%d).tar.gz" -C /home "$name"
# 7. Report files they own outside their home folder, for someone to hand over.
local others
others=$(find / -xdev -user "$name" -not -path "/home/$name" -not -path "/home/$name/*" 2>/dev/null || true)
if [ -n "$others" ]; then
say "$name owns $(printf '%s\n' "$others" | wc -l) files outside /home/$name, for someone to take over:"
printf '%s\n' "$others" | sed 's/^/ /' >&2
fi
record "removed $name: login locked and expired, keys, scheduled jobs and processes gone, home folder archived"
}
cmd_audit() {
[ $# -eq 0 ] || usage
printf '%-10s %-22s %-5s %-6s %-5s %s\n' NAME GROUPS KEYS CRON PROCS STATUS
local name groups keys cron procs status
for name in $(staff_members); do
groups=$(id -nG "$name" | tr ' ' '\n' | grep -vx -e bookshop-staff -e "$name" | paste -sd, - || true)
keys=$(grep -c . "/home/$name/.ssh/authorized_keys" 2>/dev/null || echo 0)
cron=$(crontab -l -u "$name" >/dev/null 2>&1 && echo yes || echo no)
procs=$(pgrep -u "$name" | wc -l || true)
if is_expired "$name"; then status="removed"; else status="active"; fi
printf '%-10s %-22s %-5s %-6s %-5s %s\n' "$name" "${groups:--}" "$keys" "$cron" "$procs" "$status"
done
}
cmd_sync() {
[ $# -eq 1 ] || usage
local roster=$1 line name groups key
[ -r "$roster" ] || refuse "can't read the roster $roster"
declare -A want=()
local -a adds=()
while IFS= read -r line || [ -n "$line" ]; do
[ -n "$line" ] || continue
[ "$line" = "name,groups,key" ] && continue
IFS=, read -r name groups key <<<"$line"
valid_name "$name" || refuse "roster line '$line': '$name' isn't a valid login name"
want[$name]=1
adds+=("$name $groups $key")
done <"$roster"
[ "${#want[@]}" -gt 0 ] || refuse "the roster lists nobody; that would remove everyone. Is the file empty or cut short?"
local -a removes=()
for name in $(staff_members); do
is_expired "$name" && continue
[ -n "${want[$name]:-}" ] || removes+=("$name")
done
if [ "${#removes[@]}" -gt "$MAX_REMOVALS" ]; then
refuse "the roster would remove ${#removes[@]} people (${removes[*]}), more than MAX_REMOVALS=$MAX_REMOVALS. Check the roster; if it's right, run again with MAX_REMOVALS=${#removes[@]}"
fi
local a
for a in "${adds[@]}"; do
read -r name groups key <<<"$a"
cmd_add "$name" "$groups" "$key"
done
for name in "${removes[@]}"; do
cmd_remove "$name"
done
[ "$apply" -eq 1 ] || say "dry run: nothing was changed. Add --apply to make these changes."
}
case "${1:-}" in
audit) shift; cmd_audit "$@" ;;
add) shift; cmd_add "$@"; [ "$apply" -eq 1 ] || say "dry run: nothing was changed. Add --apply to do it." ;;
remove) shift; cmd_remove "$@"; [ "$apply" -eq 1 ] || say "dry run: nothing was changed. Add --apply to do it." ;;
sync) shift; cmd_sync "$@" ;;
*) usage ;;
esac
It has four commands. add, remove and sync are dry runs unless you add --apply: they print each command they would run. The parts that matter, as we use them.
Onboard Alice
sudo staff add alice developers ~/keys/alice.pub
sudo staff add alice developers ~/keys/alice.pub --apply
2026-11-18T16:01:42Z staff: would run: useradd --create-home --shell /bin/bash --groups bookshop-staff,developers alice
2026-11-18T16:01:42Z staff: would run: usermod --lock alice
2026-11-18T16:01:42Z staff: would run: install -d -m 700 -o alice -g alice /home/alice/.ssh
2026-11-18T16:01:42Z staff: would run: install -m 600 -o alice -g alice /home/vagrant/keys/alice.pub /home/alice/.ssh/authorized_keys
2026-11-18T16:01:42Z staff: (dry run) added alice (groups: developers; key: 256 SHA256:Lbn8WDM0s0nQJQ54wu+zfHehDiayTq3iTcZltSLrlzk alice@bookshop)
2026-11-18T16:01:42Z staff: dry run: nothing was changed. Add --apply to do it.
2026-11-18T16:01:42Z staff: added alice (groups: developers; key: 256 SHA256:Lbn8WDM0s0nQJQ54wu+zfHehDiayTq3iTcZltSLrlzk alice@bookshop)
The dry run shows exactly what onboarding is:
useradd --create-home --shell /bin/bash --groups bookshop-staff,developers alice: create the login.--create-homemakes/home/alice,--shell /bin/bashsets the program she gets when she logs in, and--groupsadds her to those groups.usermod --lock alice: lock the password. She has none, and this makes sure one can't be used. She logs in with her key only.install -d -m 700 -o alice -g alice /home/alice/.ssh: make her.sshfolder (-dfor a folder), owned by her (-oowner,-ggroup), and open to her only (-m 700).install -m 600 ... authorized_keys: copy her public key intoauthorized_keys, the file SSH checks when someone logs in as her, readable and writable by her only (600).
The permissions aren't fussiness. SSH refuses to use an authorized_keys file that other people could change, because anyone who could change it could add their own key. Get them wrong and the login fails with no clear reason.
The fingerprint (SHA256:Lbn8...) is a short ID for the key. It goes in the log, so later you can tell exactly which key was given access, without storing the key in the log.
Now log in as Alice:
ssh -i ~/keys/alice -o StrictHostKeyChecking=accept-new alice@localhost 'whoami; id -nG'
sudo ls -la /home/alice/.ssh
Warning: Permanently added 'localhost' (ED25519) to the list of known hosts.
alice
alice bookshop-staff developers
total 12
drwx------ 2 alice alice 4096 Nov 18 16:01 .
drwxr-x--- 4 alice alice 4096 Nov 18 16:01 ..
-rw------- 1 alice alice 96 Nov 18 16:01 authorized_keys
ssh -i KEY USER@HOST 'COMMANDS': log in asaliceusing her private key (-ipicks the key file), run the commands, and come back.localhostmeans this same server.-o StrictHostKeyChecking=accept-new: trust this server the first time without asking.-osets an SSH option. The warning line is SSH saying it did.whoami; id -nG: who you're logged in as, and your groups (-nnames,-Gall groups).ls -la: everything in her.sshfolder, hidden files too (-a), with permissions (-l).drwx------is700, and-rw-------is600.
Alice is in, as herself, in her groups, with no password anywhere.
Bob joins, and does some work
sudo staff add bob developers,deployers ~/keys/bob.pub --apply
ssh -i ~/keys/bob -o StrictHostKeyChecking=accept-new bob@localhost 'echo "* * * * * date >> ~/still-here.log" | crontab -; nohup sleep 3600 >/dev/null 2>&1 & echo "Q4 numbers" > /srv/shared/bob-report.txt'
sudo staff audit
2026-11-18T16:02:02Z staff: added bob (groups: developers,deployers; key: 256 SHA256:5hEvwBXdRo67WTgdHzpI94p7WZq297LNhLmsoGFR/yA bob@bookshop)
NAME GROUPS KEYS CRON PROCS STATUS
alice developers 1 no 0 active
bob developers,deployers 1 yes 3 active
Bob does three ordinary things a person does in their job:
- Sets up a scheduled job.
crontab -takes a schedule from what's piped into it.* * * * *means every minute, anddate >> ~/still-here.logadds the time to a file. - Starts a program that keeps running.
nohupstops it being stopped when he logs out,&runs it in the background, and>/dev/null 2>&1throws away its output.sleep 3600stands in for any long-running job. - Leaves a file in a shared folder,
/srv/shared, where others can see it.
The audit shows all of it: Bob has 1 key, a scheduled job (CRON yes), and 3 processes.
Offboard Bob the quick way
Bob leaves. The most common "offboarding" is one command:
sudo passwd -l bob
ssh -i ~/keys/bob -o BatchMode=yes bob@localhost 'whoami'
sleep 65
sudo cat /home/bob/still-here.log
pgrep -u bob -a
passwd: password changed.
bob
Wed Nov 18 04:03:01 PM UTC 2026
2611 /usr/lib/systemd/systemd --user
2612 (sd-pam)
2646 sleep 3600
passwd -l bob: lock Bob's password (-lis "lock").-o BatchMode=yes: never ask for a password; if the key doesn't work, fail at once.sleep 65: wait just over a minute, so his scheduled job gets a chance to run.pgrep -u bob -a: every process running as Bob (-upicks the user), with its full command (-a).
After the "offboarding", all of Bob's access still works:
- He logged straight back in with his key: it printed
bob. Locking a password does nothing to SSH keys. The manual forpasswdeven says so: locking "does not disable the account", because the user may log in another way, "e.g. an SSH key". - His scheduled job ran at 16:03:01, after he'd "left".
- His program is still running, along with
systemd --userand(sd-pam), the helpers systemd starts for anyone who logs in.
Nothing here looks wrong. The account says "locked". That's what makes the quick way dangerous.
Offboard Bob properly
sudo staff remove bob
sudo staff remove bob --apply
2026-11-18T16:03:47Z staff: would run: usermod --lock --expiredate 1 bob
2026-11-18T16:03:47Z staff: would run: rm -f /home/bob/.ssh/authorized_keys
2026-11-18T16:03:47Z staff: would run: crontab -r -u bob
2026-11-18T16:03:47Z staff: bob has 3 processes running
2026-11-18T16:03:47Z staff: would run: pkill -KILL -u bob
2026-11-18T16:03:47Z staff: would run: gpasswd -d bob developers
2026-11-18T16:03:47Z staff: would run: gpasswd -d bob deployers
2026-11-18T16:03:47Z staff: would run: install -d -m 700 /var/backups/staff
2026-11-18T16:03:47Z staff: would run: tar -czf /var/backups/staff/bob-20261118.tar.gz -C /home bob
2026-11-18T16:03:47Z staff: bob owns 2 files outside /home/bob, for someone to take over:
/var/spool/cron/crontabs/bob
/srv/shared/bob-report.txt
2026-11-18T16:03:47Z staff: (dry run) removed bob: login locked and expired, keys, scheduled jobs and processes gone, home folder archived
2026-11-18T16:03:47Z staff: dry run: nothing was changed. Add --apply to do it.
2026-11-18T16:03:47Z staff: bob has 3 processes running
2026-11-18T16:03:49Z staff: bob owns 1 files outside /home/bob, for someone to take over:
/srv/shared/bob-report.txt
2026-11-18T16:03:49Z staff: removed bob: login locked and expired, keys, scheduled jobs and processes gone, home folder archived
Seven steps, each closing one door:
| Step | Command | Closes |
|---|---|---|
| 1 | usermod --lock --expiredate 1 bob | Every login. --lock locks the password; --expiredate 1 sets the account to have expired on January 2, 1970. An expired account is refused however it logs in, key or not. |
| 2 | rm -f /home/bob/.ssh/authorized_keys | His SSH key. -f means no error if it's already gone. |
| 3 | crontab -r -u bob | His scheduled jobs. -r removes, -u picks the user. |
| 4 | pkill -KILL -u bob | Everything still running as him. -KILL stops it at once. |
| 5 | gpasswd -d bob developers | Each access group. -d deletes him from the group. |
| 6 | tar -czf ... -C /home bob | Nothing: it keeps a copy of his home folder, readable by root only, in case anything in it is needed. -c creates an archive, -z compresses it, -f names the file, and -C /home works from /home. |
| 7 | find / -xdev -user bob ... | Nothing: it lists files he owns elsewhere, like his report in /srv/shared, so someone can take them over. -xdev stays on one disk. |
The dry run listed two files outside his home folder; the real run, one. His crontab file was removed in step 3, before step 7 looked. The report is left for someone to deal with, deliberately: the script can't know whether it matters.
Why not delete the account? Two reasons. Every file on Linux is owned by a number, the user ID. Delete Bob, and his number can be given to the next new starter, who then owns all of Bob's files that were missed. And a locked, expired account is a record that Bob existed and was removed. Delete the account later, after a set period such as 90 days, once his files have been dealt with.
Now check every door:
ssh -i ~/keys/bob -o BatchMode=yes bob@localhost 'whoami'
sudo crontab -l -u bob
pgrep -u bob -a || echo "nothing running as bob"
sudo staff audit
sudo ls -l /var/backups/staff
sudo cat /var/log/staff.log
bob@localhost: Permission denied (publickey,password).
no crontab for bob
nothing running as bob
NAME GROUPS KEYS CRON PROCS STATUS
alice developers 1 no 0 active
bob - 0 no 0 removed
total 4
-rw-r--r-- 1 root root 2495 Nov 18 16:03 bob-20261118.tar.gz
2026-11-18T16:01:42Z vagrant: added alice (groups: developers; key: 256 SHA256:Lbn8WDM0s0nQJQ54wu+zfHehDiayTq3iTcZltSLrlzk alice@bookshop)
2026-11-18T16:02:02Z vagrant: added bob (groups: developers,deployers; key: 256 SHA256:5hEvwBXdRo67WTgdHzpI94p7WZq297LNhLmsoGFR/yA bob@bookshop)
2026-11-18T16:03:49Z vagrant: removed bob: login locked and expired, keys, scheduled jobs and processes gone, home folder archived
crontab -l -u bob: list Bob's scheduled jobs (-l).|| echo ...:pgrepfinding nothing counts as failing, so the message prints instead.
Every door is closed, and you can show it: login refused, no scheduled jobs, nothing running, no groups, no keys, and his files archived. The log records each change, when, and who made it (vagrant), from sudo's SUDO_USER. When an auditor asks "when was Bob's access removed, and by whom?", that's the answer.
Keep the server matching a roster
Adding and removing people one command at a time works, until someone forgets one. The step up is a roster: one file listing who should have access, often exported from the HR system. A script makes the server match it, every time it runs:
sudo staff sync ~/roster.csv
sudo staff sync ~/roster.csv --apply
sudo staff audit
2026-11-18T16:03:57Z staff: alice already exists: making sure their groups and key are right
2026-11-18T16:03:57Z staff: would run: usermod -G bookshop-staff,developers alice
2026-11-18T16:03:57Z staff: would run: install -d -m 700 -o alice -g alice /home/alice/.ssh
2026-11-18T16:03:57Z staff: would run: install -m 600 -o alice -g alice /home/vagrant/keys/alice.pub /home/alice/.ssh/authorized_keys
2026-11-18T16:03:57Z staff: (dry run) checked alice (groups: developers; key: 256 SHA256:Lbn8WDM0s0nQJQ54wu+zfHehDiayTq3iTcZltSLrlzk alice@bookshop)
2026-11-18T16:03:57Z staff: would run: useradd --create-home --shell /bin/bash --groups bookshop-staff,deployers carol
...
2026-11-18T16:03:57Z staff: dry run: nothing was changed. Add --apply to make these changes.
...
NAME GROUPS KEYS CRON PROCS STATUS
alice developers 1 no 0 active
bob - 0 no 0 removed
carol deployers 1 no 0 active
- Alice was already right, and was "checked": her groups and key set again, which changes nothing. That's what makes it safe to run every hour: a second run with nothing new does nothing new.
- Carol was added.
- Bob was left alone. He's not on the roster, but he's already removed.
usermod -G: set exactly these groups (-G), so someone who changed team (a mover) loses the old group and gets the new one.
The guard rails
A sync is powerful in both directions: a bad roster removes good people. Four tests:
: > ~/empty.csv
sudo staff sync ~/empty.csv; echo "exit $?"
printf 'name,groups,key\nalcie,developers,/home/vagrant/keys/alice.pub\ncarlo,deployers,/home/vagrant/keys/carol.pub\n' > ~/typo.csv
sudo staff sync ~/typo.csv; echo "exit $?"
sudo staff add root developers ~/keys/alice.pub; echo "exit $?"
sudo staff add dave developers,admins ~/keys/alice.pub; echo "exit $?"
2026-11-18T16:04:15Z staff: refusing: the roster lists nobody; that would remove everyone. Is the file empty or cut short?
exit 2
2026-11-18T16:04:15Z staff: refusing: the roster would remove 2 people (alice carol), more than MAX_REMOVALS=1. Check the roster; if it's right, run again with MAX_REMOVALS=2
exit 2
2026-11-18T16:04:15Z staff: refusing: root exists but isn't in the bookshop-staff group: not one of ours
exit 2
2026-11-18T16:04:15Z staff: refusing: 'admins' isn't one of: developers deployers
exit 2
: > FILE: makes an empty file.:does nothing, and>creates the file. It's what a failed download of the roster looks like.printf '...\n...': writes a roster with two typos,alcieandcarlo.\nstarts a new line.echo "exit $?": prints the exit code of the command before it.2means refused.
An empty roster would have removed everyone. It's the most likely bad roster of all: a download that failed, an export that timed out. The script refuses outright.
Two typos would have removed Alice and Carol, and added two people who don't exist. MAX_REMOVALS (1 by default) stops any run that removes more people than a normal day would. If a big change is real, say a team leaving, you set it higher for that one run, on purpose.
root isn't in bookshop-staff, so the script won't touch it. And admins isn't an access group the script knows, so nobody can be given access it wasn't built to give.
Clean up
exit
(On your own computer)
vagrant destroy -f
-f deletes the server without asking.
On a real server, and beyond
- Use one central list of people, not a script per server. Most organizations use a directory (Active Directory, LDAP, or a cloud identity service) so one change reaches every server and app. A script like this is how you understand what that system does, and what's left when there isn't one.
- For many servers, use Ansible. Its
userandauthorized_keymodules do what this script does, on every server at once: see the Ansible track. - Servers are only part of it. A leaver also has cloud accounts, GitHub, email, the VPN, and any shared passwords they knew, which need changing. Keep a written checklist, and tick it off for every leaver.
- Never share logins. One login used by several people can't be taken from just one of them. Spot the problem shows why.
- Review access regularly. Run the audit monthly and ask, for each person, "should they still have this?". Movers collect access they no longer need.
- Delete removed accounts after a set time, once their files have been handed over.
Spot the problem
Work out what's wrong before you read the explanation.
"We removed him properly. How did he get in?" A team uses a script like this one, and removes Dan cleanly the day he leaves: login locked and expired, key gone, jobs and processes gone. A month later, the server's log shows someone logging in with Dan's key, as a user called deploy. What's wrong? The team has a shared deploy login, and Dan's public key was in /home/deploy/.ssh/authorized_keys too. Removing Dan's own account doesn't touch keys he was given on other accounts. The fix: no shared logins; give each person their own, and use groups and sudo for anything shared. Until then, search every authorized_keys file for the leaver's key (sudo grep -l "dan@" /home/*/.ssh/authorized_keys /root/.ssh/authorized_keys), and remove it everywhere. -l lists the files that match, and * covers every home folder.
Keep this
| To | Use |
|---|---|
| Create a login with a home folder | useradd --create-home --shell /bin/bash --groups G1,G2 NAME |
| Lock a password (not the account) | usermod --lock NAME or passwd -l NAME |
| Stop every login, key or not | usermod --expiredate 1 NAME |
| Set someone's groups exactly | usermod -G G1,G2 NAME |
| Take someone out of a group | gpasswd -d NAME GROUP |
| Install an SSH key | .ssh at 700, authorized_keys at 600, both owned by the person |
| A key's fingerprint | ssh-keygen -l -f KEY.pub |
| Someone's scheduled jobs | crontab -l -u NAME, remove with crontab -r -u NAME |
| Everything running as someone | pgrep -u NAME -a, stop with pkill -KILL -u NAME |
| Files someone owns | find / -xdev -user NAME |
| Who's in a group | getent group GROUP |
| Someone's groups | id -nG NAME |
Where you are now
You've given two people access with keys and no passwords, watched the usual one-command offboarding leave a leaver able to log in, with his job still running and his program still going, and then removed every kind of access properly, with a record of who did it. You've kept a server matching a roster, and seen the guards that stop an empty or mistyped roster removing everyone. Lesson 5 takes a different kind of manual work, the steps someone follows by hand during an incident, and turns it into a script that's safe to run under pressure.
Check yourself
After passwd -l bob, Bob logged in again. Why?
Which step stops every way of logging in, key or not?
Why does the script lock and expire Bob's account instead of deleting it?
Why does authorized_keys have to be 600 and .ssh 700?
The roster download failed and the file is empty. What should a sync do?
Alice is already set up correctly. What does syncing the roster do to her?
Key terms
- Joiners, movers and leavers: the three moments in a person's time at an organization when their access has to change.
- Offboarding: removing all of someone's access when they leave.
- Public and private key: an SSH key pair. The private key stays on the person's computer; the public key goes on the server, in
authorized_keys. - Fingerprint: a short ID for a key, safe to write in logs.
- Locked password: the password can't be used. Other ways in, like keys, still work.
- Expired account: an account refused for every kind of login.
- Roster: a list of who should have access, used as the one source of truth.
- Access review: checking regularly that everyone still needs the access they have.
Go deeper
- Earlier lessons: Permissions and users for users, groups and
chmod, and SSH and keys for how key logins work. - The Ansible track, for managing users on many servers at once.
- Manuals:
man useradd,man usermod(look for--expiredate),man passwd(look for the note under-l), andman crontab, on any Ubuntu machine. - Try: make Carol a mover: change her line in the roster from
deployerstodevelopers, sync it, and check withid -nG carolthat she's lost the old group. Then add a second key to Alice'sauthorized_keysby hand, run the sync, and see what happens to it.