Sometimes you need to allow a normal user to use a few root commands or exec scripts with root priviledges.
In Linux, to give limited root access to a user, you need to edit the /etc/sudoers file.
Do not edit the /etc/sudoers file by hand, use sudo visudo instead. visudo will open the /etc/sudoers file in your default text editor and warn you if you type something wrong, that could generate system issues.
How to give root access to a normal user, for a few commands only:
Add this line in /etc/sudoers file:
username ALL=(root) /path/to/command/,/path/to/command2/,/path/to/script
The command’s paths are separated one from another by comma (,) .
As an example, I will give to the user mike access to use useradd and groupadd:
$ whereis useradd
useradd: /usr/sbin/useradd /usr/share/man/man8/useradd.8.gz
$ whereis groupadd
groupadd: /usr/sbin/groupadd /usr/share/man/man8/groupadd.8.gz
Next, add this in the /etc/sudoers:
mike ALL = (root) /usr/sbin/useradd,/usr/sbin/groupadd
Test the useradd and groupadd commands:
$ su mike
$ sudo useradd
$ sudo groupadd
This will ask for the mike user’s password.
How to give passwordless root access to a normal user, for a few commands only:
Add this in /etc/sudoers:
username ALL=(root) NOPASSWD: /path/to/command/,/path/to/command2/,/path/to/script
To allow mike to use useradd and groupadd without being asked for his password, add this to /etc/sudoers:
mike ALL = (root) NOPASSWD: /usr/sbin/useradd,/usr/sbin/groupadd
Related reading: How to give a normal user shutdown and reboot access in Linux