Understanding sudoers File: Allowing Execution of Specific Commands for a User

Abstract: Grant users permission to run specific commands without full root access by editing the sudoers file.

Created: 2026-09-04 by
You can grant a user permission to run specific commands without full root access by editing the /etc/sudoers file or using files in the /etc/sudoers.d/ directory. This method allows you to define precise rules that map users or groups to allowed executables, often with optional password exemptions or argument restrictions.

Understanding the Sudoers File Structure

The /etc/sudoers file is the central configuration file for the sudo utility on Linux systems. It dictates who can execute what commands and under which conditions. Because this file controls system security, it must be edited carefully. Incorrect syntax can lock out all administrative access, including your own. The standard practice is to never edit this file directly with a text editor like nano or vi. Instead, always use the visudo command, which performs a syntax check before saving changes. If a syntax error is detected, visudo will abort the save operation, preventing a broken configuration. The file consists of several sections: aliases (user, host, command, and runas), defaults settings, and then the actual rule definitions. Rules follow a specific order: user host=(runas) commands. Understanding this structure is critical because later rules can override earlier ones if not configured correctly. For most administrators, creating a new file in /etc/sudoers.d/ is safer than modifying the main file. Files in this directory are included by the main sudoers file via an include directive, allowing for modular management of permissions. This approach makes it easier to audit changes and revert specific user permissions without touching the core system configuration. You can learn more about general sudo permissions in our guide on Giving User Permissions as Root Using Sudo.

Syntax for Specific Command Execution

To allow a user to execute a specific command, you need to add a line to the sudoers configuration. The basic syntax is:
username HOST=(root) NOPASSWD: /path/to/command
Let us break down each component of this line. username is the login name of the user or group you are granting access to. If you want to grant access to a group, prefix the name with a percent sign, like %groupname. HOST specifies from which hosts this rule applies. Using ALL means the rule applies regardless of where the user logs in from. (root) indicates the user identity under which the command runs. By default, sudo runs commands as root, but you can specify other users if needed. NOPASSWD is an optional tag that suppresses the password prompt. Without this tag, the user will still need to enter their own password to run the command. Finally, /path/to/command is the absolute path to the executable. Always use absolute paths to prevent users from bypassing restrictions by placing malicious scripts in their home directories with the same name. For example, to allow a user named devops to restart the Nginx service without a password, you would add:
devops ALL=(root) NOPASSWD: /usr/bin/systemctl restart nginx
This rule is highly specific. The user cannot stop Nginx, nor can they start it, unless those commands are also explicitly listed. They also cannot run systemctl status nginx unless added separately. This granularity is the primary benefit of using the sudoers file over simply adding users to the sudo group.

Using Aliases for Cleaner Configuration

As your server environment grows, managing individual lines for every command becomes unwieldy. Command aliases allow you to group multiple commands under a single name. Define an alias at the top of the sudoers file:
Cmnd_Alias WEB_SERVICES = /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx, /usr/bin/systemctl status nginx
Then, reference the alias in your user rule:
devops ALL=(root) NOPASSWD: WEB_SERVICES
This makes the configuration easier to read and maintain. You can create separate aliases for different teams or roles, such as DBA_COMMANDS or MONITORING_TOOLS.

Best Practices and Security Considerations

Security is paramount when configuring sudoers. Never use wildcards (*) in command paths unless absolutely necessary, as they can be exploited. For instance, allowing /usr/bin/vi is dangerous because users can escape to a shell within the editor. Similarly, avoid giving access to common utilities like find, less, or man without strict constraints, as they have built-in features that allow arbitrary command execution. Always test your rules in a non-production environment first. Use sudo -l as the target user to verify that the expected commands are listed in their effective privileges. If you accidentally lock yourself out, you can boot into recovery mode or use a live USB to remount the filesystem and fix the file. For more information on troubleshooting permission issues, see How did this usage of chmod break sudo access?. It is also important to understand that sudoers rules do not apply to existing sessions. If a user is already logged in, they may need to log out and back in, or open a new terminal, for the changes to take effect fully in some contexts. Additionally, remember that sudo logs all attempts, successful or failed, to syslog. Monitoring these logs is essential for auditing and detecting unauthorized access attempts.

Frequently Asked Questions

Can I allow a user to run a command with arguments?

Yes, but you must specify the exact arguments in the sudoers file. For example, /usr/bin/systemctl restart nginx only allows restarting Nginx, not stopping it. If you need to allow variable arguments, you can use ! to negate specific options or rely on aliases, but generally, specificity reduces risk.

What happens if I make a syntax error in /etc/sudoers?

If you use visudo, the editor will warn you of errors and refuse to save the file, leaving the previous configuration intact. If you edit the file manually and break it, sudo will fail entirely until you restore a valid file from a backup or recovery environment.

How do I remove a sudoers rule?

Simply delete the corresponding line from the sudoers file or the file in /etc/sudoers.d/ using visudo. There is no special "revoke" command; removing the definition removes the privilege immediately for future sudo invocations.

Why does my user still get asked for a password despite NOPASSWD?

Ensure there are no conflicting rules higher up in the file that require a password. Also, verify that the command path matches exactly, including case sensitivity. Sometimes, environmental variables or wrapper scripts can interfere with direct command matching.

Is it safe to give users access to systemctl?

Giving access to systemctl broadly is risky because it allows starting, stopping, and masking services. It is safer to restrict access to specific subcommands like restart or status for specific services, as shown in the examples above.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More