ubuntu, updated

Users

List, create, change, lock and delete user accounts, and the difference between adduser and useradd.

The basics

Every user has a name, a numeric UID, a primary group, a home folder and a login shell. It is all stored in plain text:

FileContains
/etc/passwdUsers: name, UID, GID, home, shell (no passwords)
/etc/shadowPassword hashes and expiry (root only)
/etc/groupGroups and their members

Human users start at UID 1000. Everything below is a system user for services (www-data, mysql…), usually without a login shell.

adduser or useradd?

adduseruseradd
StyleFriendly, asks questionsLow-level, does only what you pass
Home folderCreatedOnly with -m
PasswordAsks for oneNone set
Use itInteractivelyIn scripts

On Ubuntu, use adduser by hand.

Cheat sheet

WhatCommand
Create a usersudo adduser anna
Create a user (script style)sudo useradd -m -s /bin/bash -c "Anna Muster" anna
Create a system user for a servicesudo adduser --system --group --no-create-home myapp
Set / change a passwordsudo passwd anna
Make an adminsudo usermod -aG sudo anna
Delete a user (keep home)sudo deluser anna
Delete a user and home foldersudo deluser --remove-home anna
Lock an accountsudo usermod -L -e 1 anna
Unlocksudo usermod -U -e "" anna
Force password change at next loginsudo passwd -e anna
Password expiry infosudo chage -l anna
Change the login shellsudo usermod -s /bin/bash anna
Rename a usersudo usermod -l newname -d /home/newname -m anna

usermod -L only blocks password logins. The -e 1 (account expired) also blocks SSH keys.

Who is there?

WhatCommand
All usersgetent passwd
Only human usersgetent passwd | awk -F: '$3 >= 1000 && $3 < 65534 {print $1}'
Details of one userid anna
Who is logged in nowwho or w
Last loginslast -n 20
Last login per userlastlog (newer releases: lastlog2)
Failed loginssudo lastb -n 20

Before deleting a user

sudo pkill -u anna                     # end their processes
sudo find / -user anna -not -path "/proc/*" 2>/dev/null   # files outside home
sudo crontab -u anna -l                # cron jobs they own

Files left behind show a bare number instead of an owner name. A future user that gets the same UID would own them. Find them with sudo find / -nouser -not -path "/proc/*".

SSH key for a new user

sudo mkdir -p /home/anna/.ssh
echo "ssh-ed25519 AAAA... anna@laptop" | sudo tee -a /home/anna/.ssh/authorized_keys
sudo chown -R anna:anna /home/anna/.ssh
sudo chmod 700 /home/anna/.ssh && sudo chmod 600 /home/anna/.ssh/authorized_keys
§ home
~/knubertus/home/
1,1 Top