How to Create Custom Sudo Rules for Scripts in Ubuntu
This guide explains how to configure the sudoers file to allow specific users to run designated scripts with elevated privileges without entering a password. You will learn how to use the visudo command safely, define precise rules, and secure your script permissions to prevent unauthorized modifications. Following these steps ensures your Ubuntu system maintains security while automating administrative tasks.
Use Visudo to Edit Safely
Never edit the /etc/sudoers file directly with a
standard text editor. Instead, use the visudo command,
which locks the file and checks for syntax errors before saving. Open
your terminal and run:
sudo visudoDefine the Custom Rule
Scroll to the bottom of the file to add your custom rule. The syntax
follows the pattern: user host = (runas) commands. To allow
a user named john to run a specific script located at
/usr/local/bin/backup.sh without a password, add this
line:
john ALL=(ALL) NOPASSWD: /usr/local/bin/backup.shYou can also use groups by prefixing the name with a %.
For example,
%admin ALL=(ALL) NOPASSWD: /usr/local/bin/backup.sh. Save
and exit the editor. If you are using nano, press Ctrl+O
then Ctrl+X. If using vim, type :wq.
Secure the Script Permissions
Security is critical when configuring sudo rules. If the user can modify the script, they can escalate privileges to root. Ensure the script is owned by root and is not writable by others. Run the following commands:
sudo chown root:root /usr/local/bin/backup.sh
sudo chmod 700 /usr/local/bin/backup.shTest the Configuration
Verify that the rule works correctly by switching to the user account and executing the script with sudo. The command should execute without prompting for a password:
sudo /usr/local/bin/backup.shIf the command runs successfully, your custom sudo rule is active. If you receive a permission denied error, double-check the file path in the sudoers rule and ensure the script has executable permissions.