sudo: run commands as another user
sudo lets permitted users run commands as root (or as another user) with their own password. Every use is logged, so administrators can share root powers without sharing the root password.
Examples
sudo apt update # run one command as root
sudo -u postgres psql # run as another user
sudo -i # root shell with root's environment (exit to leave)
sudo -s # root shell running your $SHELL, without login scripts
sudo !! # repeat the last command with sudo (bash, zsh)
sudoedit /etc/hosts # edit a file as root using your own editor, safely
sudo -l # what am I allowed to run?
sudo -k # forget the cached password now
After you type your password, sudo remembers it for a few minutes in that terminal (5 by default, 15 on Debian and Ubuntu; set by timestamp_timeout).
Give a user sudo rights
# Debian and Ubuntu
sudo usermod -aG sudo anna
# RHEL, Fedora, Rocky, AlmaLinux
sudo usermod -aG wheel anna
# FreeBSD (sudo from packages)
sudo pw groupmod wheel -m anna
The user has to log out and in again for the new group to apply.
Write rules with visudo
Never edit /etc/sudoers with a normal editor: a syntax error can lock everyone out of sudo. visudo checks the file before saving. Put your own rules in separate files:
sudo visudo -f /etc/sudoers.d/webteam
# user/group hosts=(run as) commands
%webteam ALL=(root) /usr/bin/systemctl reload nginx, /usr/bin/systemctl restart php8.4-fpm
deploy ALL=(www-data) NOPASSWD: /usr/local/bin/deploy-site
Defaults:%webteam log_output
- Always give full paths to commands.
- Do not allow programs that can start a shell or edit arbitrary files: editors,
less,find,awk,python,tar,systemctl edit. Each of these can be turned into full root access. Usesudoeditrules for editing files. - Use
NOPASSWDonly for automation accounts with narrow rules.
Where sudo logs
sudo journalctl _COMM=sudo --since today # systemd systems
sudo grep sudo /var/log/auth.log # Ubuntu; Debian only if rsyslog is installed
sudo grep sudo /var/log/secure # RHEL
sudo or su?
su - switches to root with the root password and logs only that someone became root. sudo uses the user's own password, can be limited to certain commands, and logs each command. Ubuntu does not set a root password at all and relies on sudo. On some newer systems, run0 from systemd offers a similar function. See account security for the policy side.