核心 · Key Idea
In one line: Linux distinguishes principals via uid/gid; sudo lets a normal user temporarily borrow root privilege for specific actions. Production services should never run as root directly.
What it is#
/etc/passwd # username → uid, login shell, home dir
/etc/shadow # encrypted passwords (root-readable only)
/etc/group # group name → gid and members
/etc/sudoers # who can sudo to what
Every process is bound to a (uid, gid) pair; users can belong to many supplementary groups.
Analogy#
打个比方 · Analogy
uid is the employee number; group is the department. root (uid 0) is the CEO — has access to every room. sudo is "borrowing the CEO's key for one task" — return it after, and there's a log.
Key concepts#
rootuid 0
Superuser, bypasses permission checks. Use sparingly in prod.
Service userService User
Shell typically `/sbin/nologin` — can't log in but can run services (www-data, nginx, postgres).
Primary groupPrimary Group
Default gid at login; new files are owned by this group.
Supplementary groupsSupplementary Groups
List with `groups`. The `docker` group is a common one.
sudoswitch user do
Default target is root; `sudo -u other cmd` switches to any user.
Passwordless sudoNOPASSWD
`alice ALL=(ALL) NOPASSWD:ALL` — useful for automation but **scope it tightly**.
Common commands#
# Users
useradd -m -s /bin/bash alice # create user alice
usermod -aG docker alice # add alice to docker group
passwd alice # change password
userdel -r alice # delete user with home dir
# Groups
groupadd devs
gpasswd -a alice devs # add alice to devs
# Switch identity
su - alice # full login environment
sudo -i # full root environment
sudo cmd # single command
sudo -u postgres psql # run as a specific user
# Current identity
id
whoami
groupsHow it works#
The full sudo call path is logged (/var/log/auth.log / journalctl -u sudo).
Practical notes#
- Never blindly
chmod 4755a third-party binary — adding SUID root is like opening a back door. - Edit sudoers via
visudo— it refuses to save broken syntax, so you don't lock yourself out. - Fine-grained sudo:
alice ALL=(ALL) NOPASSWD:/usr/bin/systemctl restart nginx. - Service deploys: use systemd's
User=,Group=, orDynamicUser=to confine services. sudo -kforces re-prompt (bypasses the 5-min cache).- Audit:
sudoreplaycan replay a sudo session recording — requiresDefaults log_input,log_output.
Easy confusions#
su
**Switches to** target user's shell.
Requires the target's password.
Requires the target's password.
sudo
Executes one command **as** the target.
Requires **your** password + sudoers permission.
Requires **your** password + sudoers permission.