What it does
sudo checks the rules in /etc/sudoers and /etc/sudoers.d/. When a rule allows you, it asks for your password (not root's) and runs the command. After that it remembers you for some minutes (on RHEL 5 minutes per terminal).
Every use is logged with your real name (in /var/log/secure and the journal). This makes sudo safer than a shared root password, and with small rules you can give people only the commands they need (least privilege).
On RHEL, members of the group wheel may run every command. sudoedit (= sudo -e) edits a file safely with your own editor.
How to write it
sudo [OPTION]... COMMAND [ARGUMENT]...
sudo -i | -s [COMMAND]
sudo -l [-U USER] [COMMAND]
sudo -e FILE...
sudo -v | -k | -KOptions 31
Most used
Run commands
-i,--login- Start a login shell of the target user (like
su -).
Edit files
Check rules
Password and time stamp
Nothing matches this filter.
Examples 12
$ run as a normal user# run as root (or with sudo)
1Run one admin command
sudo dnf install -y httpd [sudo] password for student:Your own password. For the next minutes sudo does not ask again.
2Get a root shell for many tasks
sudo -i whoami rootexitwhen you are done.3See what you may run
sudo -l User student may run the following commands on server1: (ALL) ALL(ALL) ALL= full rights (wheel).4Check the rules of another user
sudo -l -U web1Test a new rule without logging in as that user.
5Run a command as another user
sudo -u postgres psql -c 'select version();'Many service tasks must run as the service account.
6Edit a system file safely
sudoedit /etc/ssh/sshd_configYour editor runs as you; only the save is done as root.
7Write to a root file from a pipe
sudo echo ... >> filefails: the redirect is done by your own shell.8Use sudo in a script without hanging
-n never waits for a password (good for cron and CI).
9Forget the password at once
sudo -kUse it before you leave your desk.
10Audit who used sudo (security)
journalctl _COMM=sudo --since todayShows user, folder and command of every sudo call.
11Find users with full rights
getent group wheel wheel:x:10:student,devops1Review this list often: everybody here is root.
12Run a command with a time limit
sudo -T 5m /usr/local/bin/cleanup.shOnly works if the rule allows it (
Defaults user_command_timeouts).
Nothing matches this filter.
Watch out
Files
/etc/sudoers- The main rules (edit only with visudo).
/etc/sudoers.d/- Extra rule files (one per team or app).
/var/log/secure- Log of sudo use.
Tips to remember
- Give rights to a group (
%webadmins), not to single users. - Use full paths in rules and
visudo -cafter every change.
Exit codes
0 :: The command ran fine (or sudo -l/-v worked). 1 :: sudo error (not allowed, wrong password, bad config). Otherwise the exit code of the command.