Skip to main content

sudo Cheatsheet

By Dejan Panovski Updated on Download PDF

sudo at a glance: running commands as root, credential caching, environment handling, sudoers rule syntax, aliases, Defaults, and logging.

The sudo command runs a single command with another user’s privileges, usually root, and the sudoers file decides who may run what. This cheatsheet covers the command options you use daily, plus the rule syntax, Defaults settings, and log locations you need when you configure sudo on a server.

Basic Usage

Run commands with elevated privileges.

CommandDescription
sudo commandRun a command as root
sudo -u username commandRun a command as another user
sudo -g groupname commandRun a command with another primary group
sudo -u#1000 commandRun as a user ID instead of a name
sudo -iOpen a root login shell that reads root’s profile
sudo -sOpen a root shell that keeps the current directory
sudo -e /etc/hostsEdit a root-owned file with an editor running as your user
sudo -b commandRun the command in the background
sudo -- command -lStop option parsing so the flags reach the command
sudo !!Re-run the previous command with sudo in Bash or Zsh

Password Caching

Control how often sudo asks for a password.

CommandDescription
sudo -vRefresh the cached credentials without running a command
sudo -kInvalidate the cache for the current terminal
sudo -KRemove the cached credentials for every terminal
sudo -n commandFail with an error instead of prompting, for cron and scripts
sudo -A commandRead the password from the program named in SUDO_ASKPASS
sudo -p "Password for %u: " commandSet a custom prompt
Defaults timestamp_timeout=10Cache the password for 10 minutes
Defaults timestamp_timeout=0Prompt for every command
Defaults timestamp_type=globalShare one timestamp across all terminals

Debian and Ubuntu packages ship a 15 minute timeout, while Fedora and RHEL keep the upstream five minute default.

Listing Privileges

Check what a rule actually grants before you rely on it.

CommandDescription
sudo -lList the commands the current user may run
sudo -llList the same rules in long form
sudo -l -U usernameList another user’s privileges as root or an authorized user
sudo -l /usr/bin/systemctlCheck whether one command is permitted
sudo -VPrint the version, and as root the full Defaults list
id -nGList group membership, which %group rules match on
getent group sudoShow the members of the sudo group

Environment Handling

sudo builds a new environment rather than passing yours through.

CommandDescription
sudo -E commandRequest preservation of the current environment
sudo --preserve-env=http_proxy commandRequest preservation of only the named variables
sudo -H commandSet HOME to the target user’s home directory
sudo envPrint the environment sudo actually builds
sudo env PATH="/opt/tool/bin:/usr/bin" commandRun with an explicit trusted PATH instead of secure_path
Defaults env_resetStrip the caller’s environment, the default on most distros
Defaults env_keep += "http_proxy https_proxy"Let named variables through env_reset
Defaults secure_path="/usr/sbin:/usr/bin:/sbin:/bin"Replace PATH for every sudo command
Defaults always_set_homeSet target HOME when env_reset does not already do so

sudo exports SUDO_USER, SUDO_UID, SUDO_GID, and SUDO_COMMAND into the command environment, so a privileged script can recover who called it.

Redirects and Pipes

The shell expands > and | before sudo runs, so redirects need their own root process.

CommandDescription
sudo echo text > /root/fileUsually fails: the shell opens the file as your user
sudo sh -c 'echo text > /root/file'Run the whole line, redirect included, as root
echo text | sudo tee /root/fileWrite the file as root
echo text | sudo tee -a /root/fileAppend to the file as root
echo text | sudo tee /root/file > /dev/nullWrite without echoing the content back
sudo sh -c 'cmd1 && cmd2'Chain several commands under one sudo call
sudo cat /root/file | grep patternRead as root, filter as your user

Editing the sudoers File

Never open /etc/sudoers in a plain editor. A syntax error there can disable sudo access.

CommandDescription
sudo visudoEdit /etc/sudoers with a syntax check on save
sudo visudo -cCheck every sudoers file without editing
sudo visudo -f /etc/sudoers.d/webopsEdit a drop-in file with the same check
sudo visudo -sTreat undefined aliases and alias cycles as errors
@includedir /etc/sudoers.dParse eligible files in the drop-in directory
sudo chown root:root /etc/sudoers.d/webopsSet the required owner and group
sudo chmod 0440 /etc/sudoers.d/webopsSet the permissions a drop-in file requires
sudo ls /etc/sudoers.dList the files in the drop-in directory

On sudo older than 1.9.1 the directive is written #includedir /etc/sudoers.d. Despite the leading #, that line is not a comment. Drop-in files whose names contain a dot or end in ~ are skipped.

visudo reads SUDO_EDITOR, VISUAL, and EDITOR when the policy lets those variables through. A command rule that matches ALL implies SETENV, while a rule granting only /usr/sbin/visudo must add SETENV or preserve the editor variables. To avoid depending on that policy, open a root shell with sudo -i, then run EDITOR=/usr/bin/vim visudo.

sudoers Rule Syntax

Each rule reads user host=(runas:rungroup) tagged commands.

RuleDescription
username ALL=(ALL:ALL) ALLFull access for one user
%sudo ALL=(ALL:ALL) ALLFull access for a group, Debian and Ubuntu
%wheel ALL=(ALL) ALLFull access for a group, Fedora and RHEL
username ALL=(ALL) NOPASSWD: ALLSkip the password prompt for every command
username ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginxSkip the prompt for one exact command
username ALL=(www-data) /usr/bin/phpRun one command as a service account
username ALL=(ALL) NOEXEC: /usr/bin/lessBlock child commands where NOEXEC is supported
username ALL=(ALL) PASSWD: /usr/bin/suForce a prompt for one command inside a NOPASSWD rule

Command paths generally must be absolute. A rule listing apt never matches; write /usr/bin/apt. Wildcards in command arguments can match whitespace, so exact arguments or anchored regular expressions are safer. Do not use an editor as a security boundary: /usr/bin/vim can start a shell even without a wildcard.

Aliases

Aliases keep long rule sets readable and reduce repetition.

DeclarationDescription
User_Alias ADMINS = alice, bob, %opsName a set of users or groups
Runas_Alias SUPERUSER = rootName a set of target users
Host_Alias WEB = web01, web02, 10.0.5.0/24Name a set of hosts
Cmnd_Alias NGINX = /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginxName a set of exact commands
ADMINS WEB=(SUPERUSER) NGINXCombine aliases in a rule
ADMINS ALL=(root) NOPASSWD: NGINXApply a tag to a command alias

Alias names start with an uppercase letter and contain uppercase letters, digits, or underscores. The parser resolves aliases across the complete policy, so a definition may appear before or after a rule that uses it.

Defaults Directives

Policy settings that apply to every matching sudo call.

DirectiveDescription
Defaults env_resetRun commands with a clean environment
Defaults secure_path="/usr/sbin:/usr/bin:/sbin:/bin"Fixed PATH for sudo commands
Defaults timestamp_timeout=15Minutes before the password is asked for again
Defaults passwd_tries=3Password attempts before sudo gives up
Defaults targetpwAsk for the target user’s password, not the caller’s
Defaults lecture=neverSkip the warning shown on first use
Defaults mail_badpassMail the administrator after a failed password
Defaults:username timestamp_timeout=30Apply a setting to one user
Defaults@web01 log_outputApply a setting on one host
Defaults!/usr/sbin/visudo env_keep += "SUDO_EDITOR VISUAL EDITOR"Preserve editor variables for visudo

Logging and Auditing

By default, sudoers logs allowed and denied commands as well as errors.

CommandDescription
sudo journalctl _COMM=sudoShow sudo events from the systemd journal
sudo journalctl -t sudo -S todayShow today’s events by syslog tag
sudo grep sudo /var/log/auth.logRead the log on Debian and Ubuntu
sudo grep sudo /var/log/secureRead the log on Fedora, RHEL, and derivatives
Defaults logfile="/var/log/sudo.log"Write a dedicated sudo log file
Defaults log_input, log_outputRecord full sessions for replay
sudo sudoreplay -lList the recorded sessions
sudo sudoreplay IDReplay one recorded session

Troubleshooting

What the common failures mean and where to look.

MessageCheck
username is not in the sudoers fileAdd the user to sudo on Debian and Ubuntu or wheel on Fedora and RHEL, then log in again
sudo: unable to resolve host nameMap the current hostname in /etc/hosts, such as 127.0.1.1 name
sudo: command not found or sudo: name: command not foundThe shell cannot find sudo, or the target command is missing or outside secure_path
sorry, you are not allowed to set the following environment variablesPreserve the variable or grant SETENV narrowly
sorry, you are not allowed to preserve the environmentGrant SETENV; matching ALL implies it unless NOSETENV overrides it
>>> /etc/sudoers: syntax error near line N <<<Press e to re-edit; Q force-saves the broken file
sudo: no tty present and no askpass program specifiedUse -n to fail fast, configure -A, or grant NOPASSWD narrowly
sudo: effective uid is not 0Check root ownership, setuid, nosuid, and NFS mounts; repair from root or recovery

Deeper reading on privilege escalation and user administration.

GuideDescription
sudo Command in LinuxFull sudo guide with examples, sudoedit, and credential caching
How to Add User to Sudoers in UbuntuGrant sudo access on Debian and Ubuntu
How to Add User to Sudoers in CentOSGrant sudo access on RHEL and derivatives
How to Run sudo Command Without PasswordSet up a NOPASSWD rule safely
su Command in LinuxSwitch user accounts instead of running one command
su cheatsheetQuick reference for su