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:
| File | Contains |
|---|---|
/etc/passwd | Users: name, UID, GID, home, shell (no passwords) |
/etc/shadow | Password hashes and expiry (root only) |
/etc/group | Groups 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?
adduser | useradd | |
|---|---|---|
| Style | Friendly, asks questions | Low-level, does only what you pass |
| Home folder | Created | Only with -m |
| Password | Asks for one | None set |
| Use it | Interactively | In scripts |
On Ubuntu, use adduser by hand.
Cheat sheet
| What | Command |
|---|---|
| Create a user | sudo adduser anna |
| Create a user (script style) | sudo useradd -m -s /bin/bash -c "Anna Muster" anna |
| Create a system user for a service | sudo adduser --system --group --no-create-home myapp |
| Set / change a password | sudo passwd anna |
| Make an admin | sudo usermod -aG sudo anna |
| Delete a user (keep home) | sudo deluser anna |
| Delete a user and home folder | sudo deluser --remove-home anna |
| Lock an account | sudo usermod -L -e 1 anna |
| Unlock | sudo usermod -U -e "" anna |
| Force password change at next login | sudo passwd -e anna |
| Password expiry info | sudo chage -l anna |
| Change the login shell | sudo usermod -s /bin/bash anna |
| Rename a user | sudo 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?
| What | Command |
|---|---|
| All users | getent passwd |
| Only human users | getent passwd | awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' |
| Details of one user | id anna |
| Who is logged in now | who or w |
| Last logins | last -n 20 |
| Last login per user | lastlog (newer releases: lastlog2) |
| Failed logins | sudo 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