sudo Explained
sudo lets regular users run commands as root (or other users). It's the gatekeeper to system-level operations.
Basic Usage
sudo runs a single command as root, then returns to your normal user.
sudo vs su
Avoid Working as Root
Don't use sudo su - and work as root. Use sudo for individual commands. This provides an audit trail and limits damage from mistakes.
How sudo Works
- Check
/etc/sudoersfor permission - If allowed, prompt for YOUR password (not root's)
- Run command as root
- Remember authentication for ~15 minutes
Check sudo Access
This shows what you're allowed to run.
The sudoers File
Never edit /etc/sudoers directly. Use visudo:
visudo checks syntax before saving - a typo in sudoers can lock you out!
sudoers Syntax
# User privilege specification
root ALL=(ALL:ALL) ALL
# Members of sudo group can run anything
%sudo ALL=(ALL:ALL) ALL
# Allow john to restart nginx without password
john ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx
# Allow deploy user to run specific commands
deploy ALL=(ALL) NOPASSWD: /bin/systemctl restart myapp, /bin/systemctl status myapp
Format: who host=(runas) commands
Common sudoers Configurations
Allow Group to Use sudo
# Anyone in admin group
%admin ALL=(ALL:ALL) ALL
No Password for Specific Commands
# Deploy user doesn't need password for these
deploy ALL=(ALL) NOPASSWD: /bin/systemctl restart myapp
Restrict to Specific Commands
# Backup user can only run backup script
backup ALL=(ALL) /usr/local/bin/backup.sh
Drop-in Configuration
Better than editing sudoers directly - add files to /etc/sudoers.d/:
Add:
deploy ALL=(ALL) NOPASSWD: /bin/systemctl restart myapp
Use sudoers.d
Files in /etc/sudoers.d/ are included automatically. Easier to manage and less risky than editing the main file.
Reset sudo Timeout
Run as Different User
Edit Files with sudo
sudoedit uses your normal editor but with elevated write permissions.
Security Best Practices
- Don't run everything as root - Only what needs it
- Use NOPASSWD sparingly - Only for specific, safe commands
- Prefer sudoers.d/ - Easier to audit and manage
- Log sudo usage - Default logging is in
/var/log/auth.log
Why should you use 'visudo' instead of directly editing /etc/sudoers?
Quick Reference
| Command | Purpose |
|---|---|
sudo command | Run as root |
sudo -u user command | Run as specific user |
sudo -l | List what you can run |
sudo -k | Forget authentication |
visudo | Safely edit sudoers |
visudo -f file | Edit sudoers.d file |
sudoedit file | Edit file as root |
Key Takeaways
sudoruns commands as root (or other users)- Always use
visudoto edit sudoers - Put custom rules in
/etc/sudoers.d/ - Use NOPASSWD only for specific, safe commands
sudo -lshows your permissions- Avoid working as root; use sudo for specific commands
Next: automating tasks with cron.