Every person and service on a Linux box is an account: a line in /etc/passwd, a password entry in /etc/shadow, group lines in /etc/group, and a home directory. Administering accounts means doing the same few things safely, every time: create with the right UID and shell, set a password policy, add groups without removing others, give narrow sudo, lock on the day someone leaves, and remove without leaving orphaned files. This lesson follows one engineer from the first day to the last.
Difficulty: Intermediate · Know this first: Lesson 10, Lesson 02
This bar adds up the admin time spent over one account's life, in minutes. It is a worked example, not a measurement. The groups and remove hops are where one careless command turns into hours.
Pick how many supplementary groups the user has and which command adds docker. See the group list afterwards.
Appended: docker added, nothing removed
Three questions. No score is saved anywhere — this is just you against the material.
Account administration grows in four levels: the commands, then safe changes, then policy, and finally accounts managed centrally for a fleet.
At the basic level you can create an account and read it back.
useradd -m -s /bin/bash alice, passwd alice, id alice, getent passwd alice./etc/passwd: name, x, UID, GID, comment, home, shell. Hashes live in /etc/shadow, readable only by root.groupadd deploy, usermod -aG deploy alice, groups alice.Where it breaks: forgetting -m leaves an account with no home directory.
Try it: Basic
useradd bob succeeded, but bob's login says "Could not chdir to home directory". Why?
Now do it: Create a test user with and without -m in a VM and compare ls -ld /home/*.
At the intermediate level you change accounts without side effects.
-aG or gpasswd -a; remove one with gpasswd -d bob docker.usermod -L -e 1), remove keys, end sessions, check crontab and running processes, find files by UID, then remove.chage for password ageing and account expiry dates.Try it: Intermediate
What is the right first step when someone leaves in a hurry?
Now do it: Write a five-line offboarding script that locks, expires, removes keys, and kills sessions for a given user.
At the advanced level accounts follow written policy.
/etc/login.defs: UID ranges, PASS_MAX_DAYS, HOME_MODE, UMASK.pam_faillock locks after repeated failures; pam_pwquality enforces password strength.useradd -r, nologin shell, no password, owned by the unit that uses them (systemd DynamicUser= creates one per run).Try it: Advanced
A service needs to run as its own user. What is the right account?
Now do it: Run getent passwd on a server and classify each account as person, service, or unknown.
At the master level accounts are not managed host by host.
Trade-off: central identity removes drift and reuse, and adds a dependency: keep a tested local break-glass account for when the directory is down.
Try it: Master
Two hosts gave the same UID to different people, and an NFS share between them now mixes their files. What prevents this?
Now do it: Compare getent passwd on two of your hosts and look for the same UID with different names.
The whole lifecycle as commands, in the order to run them. Try it in a throwaway VM or container, not on a shared server.
sudo useradd -m -s /bin/bash -c "Alice Ng" alice sudo install -d -m 700 -o alice -g alice /home/alice/.ssh echo "ssh-ed25519 AAAA... alice@laptop" | sudo tee /home/alice/.ssh/authorized_keys >/dev/null sudo chown alice:alice /home/alice/.ssh/authorized_keys; sudo chmod 600 /home/alice/.ssh/authorized_keys sudo gpasswd -a alice deploy # append, never replace sudo chage -E 2027-06-30 -M 90 -W 7 alice # expiry and ageing sudo chage -l alice; id alice
sudo usermod -L -e 1 -s /usr/sbin/nologin alice # lock, expire, no shell sudo rm -f /home/alice/.ssh/authorized_keys # keys bypass the password lock sudo pkill -KILL -u alice # end running sessions sudo crontab -l -u alice; sudo crontab -r -u alice sudo find / -xdev -uid "$(id -u alice)" -not -path "/home/alice/*" 2>/dev/null # files elsewhere # after review and archiving: sudo userdel -r alice sudo find / -xdev -nouser 2>/dev/null | head # anything left with no owner
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A one-letter group change took a team off call.
Group membership is managed only by configuration management, gpasswd -a replaces usermod in runbooks, and a check alerts when anyone in the on-call rota is missing the deploy group.
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 VM or a spare machine where you have sudo (a cloud VM, Multipass, or VirtualBox). Some commands change the system; do not run them on a shared server.
Type each one, read what it prints, and compare it with the note above it.
Create a test account with a home directory and a shell, then read it back.
sudo useradd -m -s /bin/bash -c "Lab User" labuser getent passwd labuser; id labuser; sudo ls -ld /home/labuser
Add a group safely (append, never replace) and compare with the wrong way.
sudo groupadd -f labgrp; sudo groupadd -f labdocker sudo gpasswd -a labuser labgrp; id labuser sudo usermod -G labdocker labuser; id labuser # -G without -a: labgrp is gone sudo usermod -aG labgrp labuser; id labuser
Set an expiry date and password ageing, then read them.
sudo chage -E 2027-06-30 -M 90 -W 7 labuser; sudo chage -l labuser
Offboard: lock and expire, find files by UID, then remove.
sudo usermod -L -e 1 -s /usr/sbin/nologin labuser; sudo passwd -S labuser sudo find / -xdev -uid "$(id -u labuser)" -not -path "/home/labuser*" 2>/dev/null | head sudo userdel -r labuser; sudo groupdel labgrp; sudo groupdel labdocker
accounts_audit.pyThis program audits a passwd and group file the way an access review does: it lists human accounts, flags shared or unused ones, and finds files left behind by a removed UID that a new account would inherit. Save it as accounts_audit.py, then run it.
# accounts_audit.py
passwd = """root:x:0:0:root:/root:/bin/bash
app:x:998:998:app service:/var/lib/app:/usr/sbin/nologin
alice:x:1001:1001:Alice Ng:/home/alice:/bin/bash
bob:x:1002:1002:Bob Li:/home/bob:/bin/bash
deploy:x:1003:1003:shared deploy:/home/deploy:/bin/bash
carol:x:1004:1004:Carol Diaz:/home/carol:/bin/bash"""
group = {"sudo": ["alice", "deploy"], "deploy": ["alice", "bob", "deploy"], "docker": ["bob"]}
last_login_days = {"alice": 1, "bob": 3, "deploy": 0, "carol": 140}
file_owners = {1001: 820, 1002: 310, 1003: 95, 1004: 12, 1007: 2300} # UID: files on /srv
next_uid = 1007 # what useradd would hand out next if UID 1007 had been deleted
accounts = [line.split(":") for line in passwd.splitlines()]
humans = [a for a in accounts if int(a[2]) >= 1000 and not a[6].endswith("nologin")]
names = {a[0] for a in accounts}
print(f"{len(humans)} human accounts with a login shell")
for name, _, uid, *_ in humans:
notes = []
if "shared" in dict((a[0], a[4]) for a in accounts)[name]:
notes.append("shared account: actions not attributable")
if last_login_days.get(name, 999) > 90:
notes.append(f"unused for {last_login_days[name]} days: lock it")
powerful = sorted(g for g, members in group.items() if name in members and g in {"sudo", "docker"})
if powerful:
notes.append("in " + ", ".join(powerful))
print(f" {name:<7} uid {uid} {'; '.join(notes) if notes else 'ok'}")
orphans = {uid: n for uid, n in file_owners.items() if uid not in {int(a[2]) for a in accounts}}
for uid, n in orphans.items():
print(f"UID {uid} owns {n:,} files but has no account" + ("; the next useradd would inherit them" if uid == next_uid else ""))
Run it, and you should see this output:
$ python3 accounts_audit.py 4 human accounts with a login shell alice uid 1001 in sudo bob uid 1002 in docker deploy uid 1003 shared account: actions not attributable; in sudo carol uid 1004 unused for 140 days: lock it UID 1007 owns 2,300 files but has no account; the next useradd would inherit them
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/linux-user-account-lifecycle && cd ~/labs/linux-user-account-lifecycle) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Managing User Accounts: Create, Change, Lock, Remove", 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=(
'Create a test account with a home directory and a shell, then read it back.'
'Add a group safely (append, never replace) and compare with the wrong way.'
'Set an expiry date and password ageing, then read them.'
'Offboard: lock and expire, find files by UID, then remove.'
)
step_1() {
sudo useradd -m -s /bin/bash -c "Lab User" labuser
getent passwd labuser; id labuser; sudo ls -ld /home/labuser
}
step_2() {
sudo groupadd -f labgrp; sudo groupadd -f labdocker
sudo gpasswd -a labuser labgrp; id labuser
sudo usermod -G labdocker labuser; id labuser # -G without -a: labgrp is gone
sudo usermod -aG labgrp labuser; id labuser
}
step_3() {
sudo chage -E 2027-06-30 -M 90 -W 7 labuser; sudo chage -l labuser
}
step_4() {
sudo usermod -L -e 1 -s /usr/sbin/nologin labuser; sudo passwd -S labuser
sudo find / -xdev -uid "$(id -u labuser)" -not -path "/home/labuser*" 2>/dev/null | head
sudo userdel -r labuser; sudo groupdel labgrp; sudo groupdel labdocker
}
# 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.
head, find, ls, Pipes, Redirection.Write the joiner, mover, and leaver procedure for 40 engineers and 15 service accounts on 60 Linux servers.
Where do accounts come from? How are UIDs allocated? How fast must access end when someone leaves? How do you prove to an auditor who had access last quarter?
Say 40 people, 4 joiners and 3 leavers a month, 60 hosts, and a 1-hour target from leaving to no access.
Accounts from the IdP through SSSD with central UIDs; SSH certificates for 8 hours; groups from configuration management; a leaver hook that disables the IdP account (certificates stop working within hours), plus a script to end sessions and list files by UID; service accounts as system users owned by their units; a quarterly review exported as evidence.
Central identity removes per-host drift and UID reuse, at the cost of a dependency during outages: a local break-glass account must exist and be watched. Short certificate lifetimes make leaving automatic but need a reliable issuing service.