Where to start First steps track · 15 stages
Linux Labs

sudo — running commands as another user

cheat sheet · Ubuntu 24.04 · sudo 1.9 https://lab.dimsanych.ru/en/wiki/sudo/

Cheat sheet

  • sudo apt update run a command as root
  • sudo -u postgres psql run as another user
  • sudo -i interactive root shell
  • sudo -l what I'm allowed to run
  • sudoedit /etc/nginx/nginx.conf safely edit a root-owned file
  • sudo visudo -f /etc/sudoers.d/10-x edit sudoers rules

Options

sudoers

Rights come from membership in the sudo group (Ubuntu) / wheel (RHEL), or an explicit rule. Never edit sudoers directly — only through visudo (it checks syntax, otherwise you can lock yourself out of sudo):

bash
sudo visudo                       # the main /etc/sudoers file
sudo visudo -f /etc/sudoers.d/90-deploy   # a separate drop-in (recommended)
sudo visudo -c                    # check the syntax of all files

Rule format and aliases:

# who    where = (as whom)      what
alice   ALL = (ALL:ALL)      ALL
deploy  ALL = (root) NOPASSWD: /bin/systemctl restart myapp, /bin/systemctl status myapp
%devs   ALL = (root)         /usr/bin/apt        # %group
Cmnd_Alias SERVICES = /bin/systemctl restart nginx, /bin/systemctl reload nginx
web     ALL = (root) NOPASSWD: SERVICES

NOPASSWD: — no password prompt (for automation; keep the scope narrow!).

Options and sudoedit

Useful Defaults (in /etc/sudoers.d/):

Defaults        env_reset                          # a clean environment (safe)
Defaults        secure_path="/usr/sbin:/usr/bin:/sbin:/bin"
Defaults        timestamp_timeout=15               # password cache, minutes (0 = always ask)
Defaults:deploy !requiretty
Defaults        logfile="/var/log/sudo.log"        # a separate log
bash
sudo -E cmd                       # preserve environment variables (if allowed)
sudoedit /etc/nginx/nginx.conf    # = sudo -e: safely edit a root file with your $EDITOR
sudo -v                           # extend the password cache (for long scripts)

sudoedit edits a copy under your own name and atomically puts it back — safer than sudo vim (which never runs the editor as root).

Loading…