To give a user sudo access, add them to the admin group: sudo usermod -aG sudo deploy on Debian and Ubuntu, sudo usermod -aG wheel deploy on RHEL, Fedora, and Arch, then have them log in again. This page also covers editing sudoers safely with visudo, scoping rules and passwordless sudo, running commands as another user, and the sudo lecture.
sudo usermod -aG sudo deploy # Debian / Ubuntu
sudo usermod -aG wheel deploy # RHEL / Fedora / Arch
The -a (append) is essential, as covered in add a user to a group: plain -G would wipe their other groups. The user must log out and back in for the new group to apply.
Verify it
sudo -lU deploy # what is deploy allowed to run?Once they log back in, sudo whoami from their account should print root.
Edit the sudoers file safely with visudo
A single typo in /etc/sudoers can break sudo for everyone, and if root login is disabled you are then locked out of admin entirely. That is why you never open it in a plain editor. Always use visudo, which locks the file against concurrent edits and checks the syntax before it lets you save:
sudo visudoIf you make a mistake, visudo refuses to write the broken file and offers to re-edit. That safety check is the entire point.
Use drop-in files, not the main file
Modern sudo reads everything in /etc/sudoers.d/, so the clean pattern is one small file per rule rather than editing the monolith:
sudo visudo -f /etc/sudoers.d/deployDrop-ins are easier to manage, survive package upgrades that rewrite /etc/sudoers, and are trivial to remove (just delete the file). Use -f so visudo still syntax-checks the drop-in. The main /etc/sudoers is best left close to its default.
The rule format
# user host=(runas) commands
deploy ALL=(ALL) ALL
deploy ALL=(ALL) /usr/bin/systemctl restart nginx
%webops ALL=(ALL:ALL) /usr/bin/systemctl * nginx
- user / %group who the rule is for (
%marks a group). - host where it applies (
ALL= everywhere; matters only on shared sudoers across machines). - (runas) which identities they may act as (
(ALL)= any user, including root). - commands the exact allowed commands, or
ALL.
Always use absolute paths for commands (/usr/bin/systemctl, not systemctl); a bare name can be satisfied by a malicious binary earlier on PATH.
Validate without editing
To check the whole sudoers configuration (main file plus all drop-ins), for example after writing a file from configuration management:
sudo visudo -cIt prints parsed OK or names the file and line of the problem. Run it in CI or after any automated change.
Before tightening sudo rules, keep a second root-capable session open, exactly as with disabling root login. If a rule change locks you out and root login is off, recovery means single-user mode or a rescue boot. A spare session costs nothing and saves the afternoon.
Scope sudo to specific commands
Full membership in sudo/wheel means run-anything-as-root. Often you want less than that, for example "this person may restart nginx but not become root". Do that with a drop-in:
# /etc/sudoers.d/deploy
deploy ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/systemctl status nginx
That grants exactly those two commands as root and nothing else.
For several people, point the rule at a group (prefixed with %) instead of repeating it per user:
# /etc/sudoers.d/web-ops
%webops ALL=(ALL) /usr/bin/systemctl * nginx
Then add people to webops with usermod -aG. One rule, managed by group membership.
Passwordless sudo (NOPASSWD)
Passwordless sudo is useful for automation (CI runners, deploy scripts, cron) where there is no human to type a password. It is configured with the NOPASSWD tag in a drop-in. The safe pattern is NOPASSWD on exactly the commands the automation runs, never a blanket grant:
# /etc/sudoers.d/deploy
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp, /usr/bin/systemctl status myapp
Now sudo systemctl restart myapp runs without a prompt, but the account still cannot become root or run anything else without a password. Absolute paths matter even more here.
The blanket grant, and its cost
# Convenient and dangerous: full root, no password, ever
deploy ALL=(ALL) NOPASSWD: ALL
This makes deploy equivalent to passwordless root. Anyone who lands a shell as deploy (a leaked CI token, a compromised key, a web shell running as that user) is instantly root, with no password to slow them down. Only accept this on disposable machines, or where the account is already as trusted as root and tightly isolated.
A safer middle ground for humans
If the goal is just to stop re-typing your password every few minutes, you do not need NOPASSWD at all. Raise the re-prompt timeout instead:
# /etc/sudoers.d/timeout
Defaults timestamp_timeout=60
That caches your sudo authentication for 60 minutes per terminal, so you type the password once an hour, without ever granting password-free root. For most people this is the right answer, and NOPASSWD is reserved for genuine automation. Confirm any rule with sudo -lU deploy, which marks the entries that do not require a password.
Run a command as another user
To run a single command as another user, not root, use sudo -u:
sudo -u deploy whoami
The common real cases:
sudo -u postgres psql # run a DB client as the DB's own user
sudo -u www-data php artisan migrate # run an app command as the web user
sudo -u deploy bash -c 'cd ~ && ./deploy.sh' # a small script as the deploy userRunning as the service's own user matters because files the command creates end up owned correctly. Running a web app's CLI as root, then having the web server (as www-data) unable to read the files it just wrote, is a classic self-inflicted permissions bug.
Service accounts often have nologin as their shell, so you cannot su into them interactively. sudo -u does not need a login shell, so it still works: sudo -u appsvc /opt/app/bin/worker --once runs the worker as appsvc even though nobody can log in as appsvc.
sudo -u vs su vs runuser
| Command | Needs | Runs as | Notes |
|---|---|---|---|
sudo -u user cmd | your sudo rights | target user | Per-command, audited, no target password. The usual choice. |
su - user -c 'cmd' | the target user's password (or root) | target user | Starts a login shell; needs the target's password unless you are root. |
runuser -u user -- cmd | root | target user | Like su but no PAM password prompt; for scripts run as root. |
sudo -u is the right tool interactively because it uses your credentials and is logged. runuser is the scripting tool when you are already root and want no prompt. For an interactive shell as the user:
sudo -u deploy -i # an interactive login shell as deploy
sudo -u deploy -s # a non-login shell as deploy-i simulates a full login (loads their environment and dotfiles); -s just starts a shell with the current environment.
Customize the sudo lecture
The sudo lecture is the "We trust you have received the usual lecture" message. You replace it with two Defaults lines, added through visudo:
Defaults lecture = always
Defaults lecture_file = "/etc/sudo_lecture"
The stock text is compiled into sudo itself, so you do not edit a file to change it; you override it by pointing lecture_file at your own text. lecture controls whether and how often it shows; lecture_file controls what it says. Write the message as root:
sudo tee /etc/sudo_lecture >/dev/null <<'EOF'
========================================================
This is a production server. Every sudo command is
logged with your username, the command, and a timestamp.
Think before you type. If you are not certain, stop and ask.
========================================================
EOFThen trigger it as an ordinary user. sudo -k clears the cached credential so you also see a fresh password prompt:
sudo -k
sudo whoami========================================================
This is a production server. Every sudo command is
logged with your username, the command, and a timestamp.
Think before you type. If you are not certain, stop and ask.
========================================================
[sudo] password for techearl:
root
The lecture is printed to standard error, before the password prompt: a warning the user reads before authenticating, not a receipt after the fact.
![A sudo command run as the techearl user printing a custom lecture from /etc/sudo_lecture, then the [sudo] password prompt, then the word root from the whoami output, confirming the lecture appears before authentication](https://images.techearl.com/sudo-lecture-file-linux/sudo-lecture-file-linux-demo-1280.webp)
When the lecture shows
| Value | Behavior |
|---|---|
once | Show the lecture the first time a user runs sudo, then never again (tracked per user). This is sudo's default. |
always | Show the lecture every time sudo asks for a password. The lecture is printed along with the password prompt, so it does not appear while cached credentials are still valid, or at all for NOPASSWD commands. |
never | Never show it, even if lecture_file is set. Defaults !lecture resolves to this. |
The "once" state is not stored with the credential timestamp. sudo keeps a zero-length marker per user in a lecture status directory, /var/lib/sudo/lectured/<user> on Debian and Ubuntu (/var/db/sudo/lectured on some others), and the manual says that directory should survive a reboot. So sudo -k will not bring a once lecture back; deleting the marker will:
sudo rm -f /var/lib/sudo/lectured/$USER
sudo whoami # lecture prints again, then the password promptLecture caveats
- It is a notice, not a security control. It cannot deny anything; restricting commands is the job of the scoped rules above.
lecture_filemust be readable by sudo. Keep it root-owned andchmod 644; if sudo cannot open it, it silently falls back to the built-in text.- The bytes print raw, so ANSI color codes work. That cuts both ways: only root should be able to write the file, or someone could plant terminal-control escape sequences that fire on every sudo.
- No password prompt, no lecture. sudo prints the lecture together with the password prompt, so passwordless
NOPASSWDcommands and runs inside the credential cache window (timestamp_timeout) show nothing, even withalways. If you need a notice before literally every command, the lecture is the wrong tool; test your exact config. - Scope it if needed with
Defaults:usernameorDefaults@host; the global form is what you want for a server banner.
If your goal is an audit trail, sudo already logs every command to syslog or the journal. If it is a legal "authorized use only" notice, that belongs in /etc/issue and the SSH banner, which every connection sees. The lecture earns its place as a short reminder at the moment someone reaches for root.
FAQ
They are the same idea on different distros. Debian and Ubuntu grant sudo to members of the sudo group; RHEL, Fedora, and Arch use the wheel group. Add the user to whichever your distro uses with usermod -aG.
Group membership applies at login. The user must log out and back in (or run newgrp sudo) for the new group to take effect. Confirm with groups deploy that sudo (or wheel) is listed.
visudo locks the file against concurrent edits and, crucially, runs a syntax check before saving. A malformed sudoers file can disable sudo for everyone; visudo refuses to write a broken one and lets you fix it, which a plain editor will not do.
A blanket NOPASSWD: ALL is, because anyone who gets a shell as that user becomes root with no further barrier. Scoped to specific absolute-path commands it is much safer: the account can run only those commands as root and nothing else. Scope it as tightly as the automation allows.
sudo -u user cmd runs one command as the target user using your own sudo rights, with no need for the target's password, and every use is logged. su - user starts a login shell and requires the target user's password unless you are already root. For per-command, audited switches, prefer sudo -u.
Because the default frequency is once: sudo shows the lecture the first time each user runs it, then suppresses it as long as a lecture record exists. To make it appear every time sudo prompts for a password, set Defaults lecture = always (it still stays silent for NOPASSWD commands and while cached credentials are valid); to see it once more for testing, delete your marker with sudo rm -f /var/lib/sudo/lectured/$USER.
Add Defaults lecture = never (or the negated form Defaults !lecture) via visudo. It suppresses the lecture for everyone, even if lecture_file is still set, and has no effect on password prompts or logging.
See also
- How to add a user to a group: the -aG mechanics and the -a trap.
- How to create a user on Linux: service accounts with nologin shells.
- How to disable root login: the reason to give sudo in the first place.
- Linux file permissions explained: the ownership and read bits the lecture file depends on.
- How to schedule a cron job: put the commands you run as a service account on a recurring timer.
Sources
Authoritative references this article was fact-checked against.
- sudo(8) Linux manual page (man7.org)man7.org
- sudoers(5) Linux manual page (man7.org)man7.org
- visudo(8) Linux manual page (man7.org)man7.org
- sudoers(5) manual page (sudo.ws)sudo.ws
- sudo(8) manual page (sudo.ws)sudo.ws
- sudoers_timestamp(5): time stamp and lecture status records (sudo.ws)sudo.ws
- runuser(1) Linux manual page (man7.org)man7.org





