TechEarl

How to Give a User sudo Access on Linux

Grant sudo by adding a user to the sudo or wheel group or with a sudoers drop-in, edit sudoers safely with visudo, scope rules and NOPASSWD to specific commands, run commands as another user, and customize the sudo lecture.

Ishan KarunaratnePublished ⏱️ 11 min readUpdated
Share thisCopied
Grant sudo via the sudo or wheel group, edit sudoers safely with visudo, scope NOPASSWD rules, run commands as another user, and set the sudo lecture.

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.

bash
sudo usermod -aG sudo deploy        # Debian / Ubuntu
sudo usermod -aG wheel deploy       # RHEL / Fedora / Arch
Root terminal adding a user to the sudo group with usermod -aG sudo, then sudo -lU deploy listing that the user may run all commands.
usermod -aG sudo adds the user to the admin group; sudo -lU confirms they may now run commands as root.

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

bash
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:

bash
sudo visudo

If 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:

bash
sudo visudo -f /etc/sudoers.d/deploy

Drop-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

code
# 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:

bash
sudo visudo -c

It 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:

code
# /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:

code
# /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:

code
# /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

code
# 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:

code
# /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:

bash
sudo -u deploy whoami
Root terminal showing whoami returning root, then sudo -u deploy whoami returning deploy, and sudo -u deploy id showing the deploy user's uid and groups.
sudo -u deploy runs the command with deploy's identity, not root's. id confirms the switched uid and groups.

The common real cases:

bash
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 user

Running 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

CommandNeedsRuns asNotes
sudo -u user cmdyour sudo rightstarget userPer-command, audited, no target password. The usual choice.
su - user -c 'cmd'the target user's password (or root)target userStarts a login shell; needs the target's password unless you are root.
runuser -u user -- cmdroottarget userLike 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:

bash
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:

code
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:

bash
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.
========================================================
EOF

Then trigger it as an ordinary user. sudo -k clears the cached credential so you also see a fresh password prompt:

bash
sudo -k
sudo whoami
code
========================================================
  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
The custom lecture prints before the password prompt, then sudo whoami returns root. Real output with Defaults lecture = always pointed at /etc/sudo_lecture.

When the lecture shows

ValueBehavior
onceShow the lecture the first time a user runs sudo, then never again (tracked per user). This is sudo's default.
alwaysShow 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.
neverNever 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:

bash
sudo rm -f /var/lib/sudo/lectured/$USER
sudo whoami        # lecture prints again, then the password prompt

Lecture caveats

  • It is a notice, not a security control. It cannot deny anything; restricting commands is the job of the scoped rules above.
  • lecture_file must be readable by sudo. Keep it root-owned and chmod 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 NOPASSWD commands and runs inside the credential cache window (timestamp_timeout) show nothing, even with always. 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:username or Defaults@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

Sources

Authoritative references this article was fact-checked against.

TagsLinuxsudosudoersvisudowheelNOPASSWDrunuserSecuritySystem Administration

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Schedule a cron job on Linux with crontab: the five-field schedule, PATH and day-of-week gotchas, and WordPress WP-Cron driven by a real system cron.

How to Schedule a Cron Job on Linux

Schedule a recurring task on Linux with cron: open your crontab, write the five-field schedule, point it at a command, and avoid the environment and day-of-week traps. Plus WordPress scheduling with WP-Cron and a real crontab.

Disable root login over SSH and the console, lock the root password, switch sshd to keys only, and add a pre-auth banner without locking yourself out.

How to Disable Root Login on Linux

Disable direct root login over SSH and on the console, lock the root password, switch sshd to key-only authentication, audit its algorithms with ssh_scan, and add a pre-auth login banner, without locking yourself out.