Allow a user to sudo execute a script without password

From WickyWiki


Allow a user to execute a specific script with sudo without this user needing the root password.

NOTE:

  • For security reasons this script should provide limited access. For example, if the user is able to modify this script, he/she will have root access to the system!
  • Consider adding your own settings in directory /etc/sudoers.d/ instead of directly modifying visudo. For an example go here: Temporarily disable Pi-Hole.


Example script

Example script, this assumes there is a user 'user1':

nano /home/user1/test-sudo.sh
#!/bin/bash
sudo whoami

Make executable:

sudo chmod +x /home/user1/test-sudo.sh

Make sure only root can edit this script. Again, this is very important!

sudo chown root.root /home/user1/test-sudo.sh

Example, sudoers file

Now we are going to edit the sudoers file with the 'visudo' tool. Add the following line at the bottom:

sudo visudo
...
user1 ALL=NOPASSWD: /home/user1/test-sudo.sh

Note:

  • This line means: allow user user1 to execute /home/user1/test-sudo.sh with sudo on ALL hosts without password
  • Always use visudo as it includes a syntax check. If you save a corrupt file you can not use sudo and you can not fix the problem easily
  • You can also create a new file as described in the sudoers file

Test

Login to a new terminal as 'user1'. The following will execute the script and return 'root':

sudo /home/user1/test-sudo.sh

While the following will require the sudo password:

sudo whoami

See also