sudo. This approach enforces the principle of least privilege and keeps your system secure.
Why Use sudo?
- Grants temporary elevated rights without sharing the root password
- Provides an audit trail of executed commands
- Limits users to only the commands they need
Attempting a Restricted Operation
Withoutsudo, installing packages fails:
Elevate with sudo
Prependsudo, authenticate with your own password, and the command succeeds:
If you see
User michael is not in the sudoers file, add your user to the sudo group or update /etc/sudoers accordingly.Configuring sudo: /etc/sudoers
Allsudo policies live in /etc/sudoers and included files under /etc/sudoers.d/. Always edit with visudo to prevent syntax errors:
| Field | Description | Example |
|---|---|---|
| User or Group | Username (e.g., mark) or group (%sudo) | %admin |
| Host(s) | Hosts where the rule applies (usually ALL) | localhost |
| Run-As Specification | User and group for command execution (in ( and )) | (ALL:ALL) |
| Commands | Allowed commands or ALL for full rights | /usr/bin/shutdown -r now |
| Comments | Lines beginning with # are ignored | # User privilege specification |
Never edit
/etc/sudoers with a regular text editor. Syntax errors can lock out all sudo access. Always use visudo.Best Practices for sudo Configuration
- Grant only the commands necessary for a task
- Use group-based rules to simplify management
- Avoid
NOPASSWDunless automation requires it - Keep custom rules in
/etc/sudoers.d/for modularity
Hands-On Exercises
- Create a test user:
- Add the user to the
sudogroup: - Switch to
boband install a package: - Customize a rule in
/etc/sudoers.d/custom_rulesto allowbobto restart services without a password.