To set up a user with limited sudo rights, you need to define a specific rule in the sudoers configuration. Instead of granting ALL permissions, you specify the exact command paths the user is allowed to run.
Here is a step-by-step example where we create a user named operator who can only restart the SSH service.
1. Create the new user
First, create the user and set a password:
sudo useradd operator
sudo passwd operator
(Enter a simple password like linux123 when prompted.)
2. Create a limited sudo rule
The safest way to add a rule is to create a new file in the /etc/sudoers.d/ directory. We will name the file after the user.
sudo visudo -f /etc/sudoers.d/operator
3. Add the permission line
In the editor that opens, add the following line:
operator ALL=(root) /usr/bin/systemctl restart sshd
Breakdown of this line:
operator: The username.ALL: The host (applies to all machines if the file is shared).(root): The user thatoperatorcan act as./usr/bin/systemctl restart sshd: The ONLY command this user is allowed to run withsudo.
Save and exit (if using nano, press Ctrl+O, Enter, then Ctrl+X).
4. Test the limited access
Now, switch to the operator user to test it:
su - operator
Try the allowed command:
sudo systemctl restart sshd
(It should work after you enter the operator's password.)
Try a forbidden command:
sudo cat /etc/shadow
Result: The system will block this and say:
Sorry, user operator is not allowed to execute '/bin/cat /etc/shadow' as root on host.
Summary Tips:
- Always use full paths: Use
/usr/bin/systemctlinstead of justsystemctlfor security. - Multiple commands: You can list multiple commands separated by commas:
operator ALL=(root) /usr/bin/yum update, /usr/bin/systemctl restart sshd - No Password: If you don't want the user to type a password for that specific command, use:
operator ALL=(root) NOPASSWD: /usr/bin/systemctl restart sshd
This approach follows the Principle of Least Privilege, ensuring users only have the power they absolutely need!