Skip to main content

Linux and servers · Intermediate · 18 min

Lock, expire and remove Linux user accounts safely

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · shadow 4.17.4 · OpenSSH

You will offboard a practice account on Ubuntu 26.04 by expiring it so SSH keys stop working, listing and cutting everything it still reaches, archiving its home, deleting it, and wrapping the routine in a checklist script.

On this page

When a colleague leaves, their account has to stop working the same day, and it has to stop working for every way in, not only the password. Most people reach for passwd -l first. On Ubuntu that locks the password and nothing else: an SSH key in ~/.ssh/authorized_keys still logs in. The account also tends to own things outside its home directory, such as a cron job, a sudo rule, files in /srv, and copies of its key in shared accounts. Deleting the account without finding those first leaves holes or orphaned files.

In this tutorial you build a small offboarding scene on your own server and take it apart in a safe order:

  1. Lock the password, and prove that a key still gets in.
  2. Expire the account, and prove that the key no longer does.
  3. List everything the account owns or can reach.
  4. Archive what you must keep.
  5. Cut the remaining access, then delete the account.
  6. Turn the routine into a script you can run next time.

The commands come from the passwd package (shadow 4.17.4 on Ubuntu 26.04) and OpenSSH. Every step uses throwaway practice accounts called leaver, shared-demo and leaver2, so nothing you already rely on is touched.

Step 1 · Build a practice account to offboard

Create the account that plays the colleague who is leaving, and give it a password:

Bash
sudo useradd -m -s /bin/bash -c "Practice leaver" leaver
Bash
sudo passwd leaver

Now give it an SSH key. On a real offboarding the key lives on the colleague's laptop; here you make a throwaway pair in a demo folder on the server, with no passphrase. You also make a second key that stands for the rest of the team.

Bash
mkdir -p ~/leaver-demo
ssh-keygen -q -t ed25519 -N '' -C leaver@laptop -f ~/leaver-demo/id_ed25519
ssh-keygen -q -t ed25519 -N '' -C team@ops -f ~/leaver-demo/team_ed25519
sudo install -d -m 700 -o leaver -g leaver /home/leaver/.ssh
sudo install -m 600 -o leaver -g leaver ~/leaver-demo/id_ed25519.pub /home/leaver/.ssh/authorized_keys

Many teams also have a shared account, such as deploy, that several people's keys can log in to. Make a practice one and put both keys in it:

Bash
sudo useradd -m -s /bin/bash -c "Shared account (practice)" shared-demo
sudo install -d -m 700 -o shared-demo -g shared-demo /home/shared-demo/.ssh
sudo install -m 600 -o shared-demo -g shared-demo /dev/null /home/shared-demo/.ssh/authorized_keys
cat ~/leaver-demo/team_ed25519.pub ~/leaver-demo/id_ed25519.pub | sudo tee -a /home/shared-demo/.ssh/authorized_keys >/dev/null

Finally, give leaver the kinds of things a real account collects: a nightly cron job, a sudo rule, a folder of files outside its home, and a process that keeps running.

Bash
echo '30 2 * * * /usr/bin/true' | sudo crontab -u leaver -
sudo install -m 440 /dev/null /etc/sudoers.d/60-leaver
echo 'leaver ALL=(root) /usr/bin/systemctl restart nginx' | sudo tee /etc/sudoers.d/60-leaver >/dev/null
sudo install -d -o leaver -g leaver /srv/reports-demo
sudo install -m 644 -o leaver -g leaver /dev/null /srv/reports-demo/weekly.csv
Bash
sudo -b -u leaver sleep 3600 >/dev/null 2>&1

Check it worked

Log in as leaver with its key:

Bash
ssh -i ~/leaver-demo/id_ed25519 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new leaver@localhost whoami

It prints leaver without asking for a password. If it prints Permission denied (publickey), check whether your /etc/ssh/sshd_config limits logins with AllowUsers or AllowGroups (as /tutorials/harden-ssh-on-ubuntu-26-04 suggests). Those rules refuse the practice accounts whatever their state, so the SSH checks in this tutorial will not show the difference; the account commands still work.

Step 2 · Give a temporary account an end date

You can often see a departure coming: a contract ends, an intern's placement finishes. Set the end date when you create the account and nobody has to remember it later. chage sets the expiry date (-E) and the password ageing rules (-M, the most days a password stays valid, and -W, how many days of warning the user gets).

Bash
sudo chage -E "$(date -d '+30 days' +%F)" -M 90 -W 14 leaver
sudo chage -l leaver

Ageing is about how often the password must change. The expiry date is the one that ends the account: from that day, every login is refused, keys included. Step 4 shows that in action. To clear an expiry date, use sudo chage -E -1 leaver.

Check it worked

In the chage -l output, Account expires shows a date 30 days from today, Maximum number of days between password change shows 90 and Number of days of warning before password expires shows 14.

Step 3 · Lock the password and see why it is not enough

Locking is the reflex move, so try it:

Bash
sudo passwd -l leaver
sudo passwd -S leaver

passwd -l puts a ! in front of the stored password hash, so no typed password can match it. The second field of passwd -S is now L (locked) instead of P (usable password). sudo usermod -L leaver does the same thing.

Now ask the SSH server how it is configured:

Bash
sudo sshd -T | grep -i '^usepam'

It prints usepam yes, Ubuntu's default. With PAM on, OpenSSH leaves account checks to PAM, and PAM's checks are about expiry and ageing, not a ! in the password field. A key login never uses the password, so it is not affected. The passwd manual says this itself: locking "does not disable the account", and the user may still log in with an SSH key.

Check it worked

Try the key again:

Bash
ssh -i ~/leaver-demo/id_ed25519 -o IdentitiesOnly=yes leaver@localhost whoami

It still prints leaver. The password is locked, and the colleague still has a way in. Keep the lock anyway: it stops password logins and su, but it is only half of the job.

Step 4 · Expire the account so keys stop working

Set the expiry date to day 1 of the Unix calendar, 2 January 1970. Any date in the past works; 1 is the form the passwd manual recommends.

Bash
sudo usermod -e 1 leaver
sudo chage -l leaver | grep 'Account expires'

Do not use 0 instead. The shadow(5) manual warns that 0 can be read either as "never expires" or as 1 January 1970, depending on the program reading it.

Expiry does not close sessions that are already open, and it does not stop processes the account left running. Step 7 deals with those. If you expired the wrong account, sudo usermod -e '' leaver clears the date again.

Check it worked

chage -l shows Account expires as Jan 02, 1970 or similar. Try the key once more:

Bash
ssh -i ~/leaver-demo/id_ed25519 -o IdentitiesOnly=yes leaver@localhost whoami

This time the login fails, and the server's log (sudo journalctl -u ssh --since "5 minutes ago") shows something like Access denied for user leaver by PAM account configuration. The account is closed for every login method that goes through PAM, which on Ubuntu is all of them.

Step 5 · Find everything the account owns or can reach

An expired account can still matter. Its crontab is still there: cron checks the account through PAM (/etc/pam.d/cron for the cron package, /etc/pam.d/crond if you use cronie instead) and skips the jobs while the account is expired, but they run again the moment someone clears the expiry date. Its sudo rule waits for the account to come back. Its key may open other accounts. Work through the list below and keep the output: it is your offboarding record.

Start with who the account is and which groups it is in. Save its UID too; you need it after the account is gone.

Bash
id leaver
LEAVER_UID=$(id -u leaver)
echo "$LEAVER_UID"

Scheduled jobs, running processes and sudo rules:

Bash
sudo crontab -l -u leaver
pgrep -u leaver -a
sudo grep -rnw leaver /etc/sudoers /etc/sudoers.d

The grep finds rules that name the user. It does not find rules for a group the user is in (lines starting with %), so compare the groups from id with the % lines in the same files.

The keys the account accepts, and any other account that accepts the same keys:

Bash
sudo ssh-keygen -lf /home/leaver/.ssh/authorized_keys
sudo awk '{for (i = 1; i < NF; i++) if ($i ~ /^(ssh-|ecdsa-|sk-)/) { print $(i + 1); break }}' /home/leaver/.ssh/authorized_keys > ~/leaver-demo/leaver-keys.txt
sudo find /root /home -path '*/.ssh/authorized_keys' -exec grep -lFf ~/leaver-demo/leaver-keys.txt {} +

The awk line pulls out the base64 body of each key, skipping any options written in front of it. The find then searches every account's authorized_keys for those bodies. Match on the body, not the comment: anyone can edit a comment. If your sshd_config sets a different AuthorizedKeysFile, search that path as well.

Files outside the home directory:

Bash
sudo find / -xdev -user leaver -not -path /home/leaver -not -path '/home/leaver/*'

-xdev keeps find on the root filesystem, so it skips /proc and network mounts. If your server has separate partitions for /home, /var or /srv (findmnt --real lists them), add each mount point after the /.

Check it worked

You have a short list that matches what you set up in Step 1:

  • id shows leaver's UID and its own group.
  • crontab -l prints the 30 2 * * * line, and pgrep shows the sleep 3600 process.
  • grep finds the rule in /etc/sudoers.d/60-leaver.
  • The key search lists two files: /home/leaver/.ssh/authorized_keys and /home/shared-demo/.ssh/authorized_keys. The second one is the hole that locking and expiry left open.
  • The file search shows /srv/reports-demo, /srv/reports-demo/weekly.csv and the crontab in /var/spool/cron/crontabs/leaver.

Step 6 · Archive the home directory and crontab

Before you delete anything, keep a copy. A colleague's home directory can hold scripts the team still needs, and your company may have to keep work records for a set time. Make a private folder that only root can read, then archive into it:

Bash
sudo install -d -m 700 /var/backups/offboarding
ARCHIVE="/var/backups/offboarding/leaver-$(date +%F).tar.gz"
sudo tar -czpf "$ARCHIVE" -C /home leaver
sudo sh -c 'crontab -l -u leaver > /var/backups/offboarding/leaver-crontab.txt'

The crontab is saved with sudo sh -c so that the redirect into the root-only folder also runs as root.

Home directories hold personal data. Keep the archive only as long as your policy says, and delete it on schedule. In Nigeria, the Nigeria Data Protection Act 2023 applies to that data, and other African countries have similar laws. If you copy the archive off the server over a metered or prepaid connection, check its size with sudo ls -lh "$ARCHIVE" first.

Check it worked

Bash
sudo tar -tzvf "$ARCHIVE"
sudo cat /var/backups/offboarding/leaver-crontab.txt

The listing shows leaver/, leaver/.ssh/authorized_keys and the dotfiles from /etc/skel, with leaver as their owner. The text file holds the cron line.

Step 7 · Cut the access that lives outside the account

Deleting the account would not remove its key from the shared account, and would leave the files in /srv owned by a number that belongs to nobody. Deal with each item from the inventory.

Remove leaver's keys from the shared account. The loop deletes only the lines that contain one of the saved key bodies, after a backup copy:

Bash
sudo cp -p /home/shared-demo/.ssh/authorized_keys /home/shared-demo/.ssh/authorized_keys.bak
while read -r body; do
  [ -n "$body" ] || continue
  sudo sed -i "\|$body|d" /home/shared-demo/.ssh/authorized_keys
done < ~/leaver-demo/leaver-keys.txt
sudo ssh-keygen -lf /home/shared-demo/.ssh/authorized_keys

The last command lists one key, team@ops. The [ -n "$body" ] guard matters: an empty pattern would match, and delete, every line.

Remove the cron job and the sudo rule, then check the sudoers files still parse:

Bash
sudo crontab -r -u leaver
sudo rm /etc/sudoers.d/60-leaver
sudo visudo -c

Give the files in /srv to the account that will look after them. Here that is the shared account; on your server it might be a service account or a colleague.

Bash
sudo chown -R shared-demo:shared-demo /srv/reports-demo

Stop everything still running as leaver. This ends its open SSH sessions too, so make sure the user name is right before you press Enter.

Bash
sudo pkill -KILL -u leaver

Check it worked

Bash
pgrep -u leaver -a || echo "no processes left"
sudo find / -xdev -user leaver -not -path /home/leaver -not -path '/home/leaver/*'

pgrep prints no processes left and the file search prints nothing. Logging in to shared-demo with leaver's key is refused, while the team key still works:

Bash
ssh -i ~/leaver-demo/id_ed25519 -o IdentitiesOnly=yes shared-demo@localhost whoami
ssh -i ~/leaver-demo/team_ed25519 -o IdentitiesOnly=yes shared-demo@localhost whoami

Step 8 · Delete the account and record its UID

Many teams keep an offboarded account locked and expired for an agreed period before deleting it, in case someone needs a file or an audit asks a question. When that period is over, delete it.

userdel -r deletes the home directory and the mail spool for good. Check that the archive from Step 6 exists and opens before you run it. Files on other filesystems are not removed; the inventory you did is what catches those.

Bash
sudo userdel -r leaver

It may print a warning that the mail spool (/var/mail/leaver) was not found. That is harmless: the account never received local mail. If it refuses with user leaver is currently used by process, run the pkill line again.

Now write the removal down, with the UID you saved in Step 5:

Bash
echo "$(date +%F) leaver uid=$LEAVER_UID removed by $(whoami)" | sudo tee -a /var/backups/offboarding/removed-accounts.log

Why the UID matters: Linux stores a number on each file, not a name. useradd gives a new account the smallest UID that is greater than every existing user's UID. If leaver had the highest UID on the server, the next account you create gets the same number, and with it any file that still carries that number, in backups, on shared storage or on another server that mounts this one's disks. Reassigning files before deletion (as you did in Step 7) prevents that. The log lets you answer "whose files were these?" later, and if you want a UID never to come back, create new accounts with an explicit useradd -u above the numbers in that log.

Check it worked

Bash
getent passwd leaver || echo "leaver is gone"
sudo find / -xdev \( -nouser -o -nogroup \) -print

The first command prints leaver is gone. The second lists files whose owner or group no longer exists; for this practice it prints nothing. On an older server it may list files from earlier removals that nobody reassigned: decide who owns them now.

Step 9 · Turn the routine into a checklist script

The safe, reversible part of offboarding (lock, expire, stop processes, list what is left) is the same every time. Put it in a script. Deletion stays a manual decision.

Bash
sudo tee /usr/local/sbin/offboard >/dev/null <<'EOF'
#!/usr/bin/env bash
# offboard: lock and expire one account, stop its processes,
# then list what it still owns or can reach. Deletes nothing.
set -euo pipefail

user="${1:?usage: offboard <username>}"

if [ "$(id -u)" -ne 0 ]; then echo "Run this with sudo." >&2; exit 1; fi
if ! id "$user" >/dev/null 2>&1; then echo "No such user: $user" >&2; exit 1; fi
uid="$(id -u "$user")"
if [ "$uid" -lt 1000 ]; then echo "Refusing: $user is a system account (UID $uid)." >&2; exit 1; fi
if [ "$user" = "${SUDO_USER:-}" ]; then echo "Refusing: that is your own account." >&2; exit 1; fi
home="$(getent passwd "$user" | cut -d: -f6)"

echo "== Offboarding $user (UID $uid) on $(hostname) at $(date -Is)"
usermod -L -e 1 "$user"
pkill -KILL -u "$user" || true
passwd -S "$user"
chage -l "$user" | grep 'Account expires'

echo "== Groups"
id "$user"

echo "== sudo rules naming $user (check % group rules too)"
grep -rnw -- "$user" /etc/sudoers /etc/sudoers.d || echo "  none"

echo "== Crontab"
crontab -l -u "$user" 2>/dev/null || echo "  none"

echo "== Keys in $home/.ssh/authorized_keys"
keys_file="$home/.ssh/authorized_keys"
if [ -f "$keys_file" ]; then
  ssh-keygen -lf "$keys_file" || echo "  (no readable keys)"
  echo "== Other authorized_keys files holding one of these keys"
  bodies="$(mktemp)"
  awk '{for (i = 1; i < NF; i++) if ($i ~ /^(ssh-|ecdsa-|sk-)/) { print $(i + 1); break }}' "$keys_file" > "$bodies"
  if [ -s "$bodies" ]; then
    find /root /home -path '*/.ssh/authorized_keys' -not -path "$keys_file" \
      -exec grep -lFf "$bodies" {} + || echo "  none"
  else
    echo "  none"
  fi
  rm -f "$bodies"
else
  echo "  none"
fi

echo "== Files owned outside $home (root filesystem only)"
find / -xdev -user "$user" -not -path "$home" -not -path "$home/*" -print || true

echo "== Next: archive $home, remove the items above, then decide on userdel -r."
EOF
sudo chmod 755 /usr/local/sbin/offboard

The guards at the top refuse system accounts, unknown names and your own account, so a typo cannot lock you out. pkill ... || true keeps the script going when the account has no processes.

Try it on a fresh practice account whose key, like before, also sits in the shared account:

Bash
sudo useradd -m -s /bin/bash leaver2
sudo install -d -m 700 -o leaver2 -g leaver2 /home/leaver2/.ssh
sudo install -m 600 -o leaver2 -g leaver2 ~/leaver-demo/id_ed25519.pub /home/leaver2/.ssh/authorized_keys
cat ~/leaver-demo/id_ed25519.pub | sudo tee -a /home/shared-demo/.ssh/authorized_keys >/dev/null
sudo offboard leaver2 | sudo tee "/var/backups/offboarding/leaver2-$(date +%F).txt"

Check it worked

The report shows leaver2 L from passwd -S, an Account expires date in 1970, and under "Other authorized_keys files" the line /home/shared-demo/.ssh/authorized_keys: the script found the same hole you found by hand. The report is also saved in /var/backups/offboarding/.

When you are done practising, remove everything this tutorial created. Read the list first: userdel -r and rm -rf cannot be undone, and the last three lines delete the practice archives and the log. Keep the offboard script if you want it. To remove it too, run sudo rm /usr/local/sbin/offboard.

Bash
sudo userdel -r leaver2
sudo userdel -r shared-demo
sudo rm -rf /srv/reports-demo
rm -rf ~/leaver-demo
sudo sh -c 'rm -f /var/backups/offboarding/leaver*'
sudo rm /var/backups/offboarding/removed-accounts.log
sudo rmdir /var/backups/offboarding

rmdir refuses if the folder holds anything else, which is what you want on a server where it already existed.

Next steps

  • Make the sudo rules you remove at offboarding narrow in the first place: /tutorials/write-least-privilege-sudo-rules-with-visudo
  • Limit who may log in over SSH at all with AllowGroups, so a forgotten account has less reach: /tutorials/harden-ssh-on-ubuntu-26-04
  • Revisit how accounts and keys are set up for new joiners: /tutorials/create-a-sudo-user-on-ubuntu-26-04 and /tutorials/log-in-to-a-server-with-ssh-keys

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.