To restrict commands for a user in Linux using sudo, you can specify which commands a user is allowed to execute in the /etc/sudoers file. Here’s how to do it:
1. Open the sudoers File Safely:
Always use the visudo command to edit the sudoers file. This ensures that syntax errors are checked before saving.
sudo visudo
2. Specify User and Allowed Commands:
You can restrict a user to specific commands by adding an entry in the sudoers file. The syntax is as follows:
username ALL=(ALL:ALL) /path/to/command1, /path/to/command2
3. Example:
Suppose you want to allow a user named bob to only run the systemctl and ls commands. You would add the following line:
bob ALL=(ALL:ALL) /bin/systemctl, /bin/ls
4. Denying All Other Commands:
By default, if a user tries to run a command not listed in the sudoers file, they will be denied access. Therefore, simply specifying the allowed commands will restrict the user from executing any other commands.
5. Testing the Configuration:
After saving your changes, test the configuration by switching to the user and attempting to run both allowed and disallowed commands:
sudo systemctl status # Allowed
sudo ls # Allowed
sudo rm -rf / # Not allowed (should return an error)
Important Notes:
- Be Specific: Ensure you specify the full path to the commands to avoid ambiguity.
- Use Wildcards: If you want to allow a user to run all commands in a specific directory, you can use wildcards. For example:
This allowsbob ALL=(ALL:ALL) /usr/bin/*bobto run any command in the/usr/bindirectory.
If you have any further questions or need more examples, feel free to ask!
