sudoers File Basics
Bash
# Never edit this file directly — use visudo
sudo visudo
# Edit a specific file
sudo visudo -f /etc/sudoers.d/myuservisudo checks syntax before saving, which prevents sudo from locking you out due to a bad configuration.
sudoers Syntax
CODE
user host=(runas_user:group) commandSUDOERS
# root can do everything
root ALL=(ALL:ALL) ALL
# Full sudo for the deploy user (password required)
deploy ALL=(ALL:ALL) ALL
# sudo for the wheel group
%wheel ALL=(ALL) ALL
# Skip the password prompt for sudo
deploy ALL=(ALL) NOPASSWD: ALL
# Allow only specific commands
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/systemctl status nginx
# Deny specific commands (append with ! after the allow list)
deploy ALL=(ALL) ALL, !/bin/su, !/usr/bin/passwd rootUsing /etc/sudoers.d/ (Recommended)
Managing drop-in files instead of the main sudoers file makes changes easier to track.
Bash
# Create the file
sudo visudo -f /etc/sudoers.d/deploy
# Contents
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp
# Set permissions (required)
sudo chmod 440 /etc/sudoers.d/deployLeast-Privilege Examples
SUDOERS
# CI/CD user — allow restarting specific services only
ci-runner ALL=(ALL) NOPASSWD: \
/usr/bin/systemctl restart myapp, \
/usr/bin/systemctl reload nginx
# DBA — PostgreSQL commands only
dbadmin ALL=(postgres) NOPASSWD: /usr/bin/psql, /usr/bin/pg_dump
# Monitoring — read-only commands only
monitor ALL=(ALL) NOPASSWD: \
/usr/bin/systemctl status *, \
/usr/bin/journalctl -u *, \
/bin/cat /var/log/*Auditing sudo Logs
Bash
# Ubuntu (journald)
sudo journalctl -u sudo | grep -i "command"
# Watch all sudo commands in real time
sudo journalctl -f | grep sudo
# Check /var/log/auth.log (Ubuntu)
grep "sudo:" /var/log/auth.log | tail -50
# /var/log/secure (CentOS)
grep "sudo:" /var/log/secure | tail -50
# sudo history for a specific user
grep "sudo:.*deploy" /var/log/auth.logsudo Timeout Settings
SUDOERS
# Change the default timeout (minutes; 0 = always prompt)
Defaults timestamp_timeout=5
# Use sudo without re-authenticating the session
Defaults timestamp_type=global
# Per-terminal timeout
Defaults timestamp_type=ttyEmergency Recovery — When sudo Is Locked Out
Bash
# After booting into single-user mode
mount -o remount,rw /
visudo # or edit directly
# Restore /etc/sudoers from backup
cp /etc/sudoers.bak /etc/sudoersEditorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)Linux man pages ↗OWASP documentation ↗
Questions & answers
Ask a question about this guide. We'll review and reply.