
Enabling users to run commands as root without being prompted for `sudo` password (Non-Interactive Mode).
Quite a few times in Linux administration you will come across a scenario where you need to run a shell command through a bash script, in an automated manner (unattended). The purpose can be as simple as restarting a system service, moving files & folders, or performing complex firewall administration tasks. In either case, you will notice that whenever you attempt to execute such system commands using the sudo
keyword that requires privileges, the system will prompt you for a password. When you wish to execute bash scripts from other programs etc, unattended, the password prompt is absolutely unacceptable and obtrusive.
Fortunately, the Linux ecosystem does have a way for us to work around this issue. On Linux, to edit the sudo
command’s configuration, we can either execute the visudo command or edit the file /etc/sudoers. But note that both of them require root permission to save the changes.
1. Allow All Users to Execute a Program as root Without Asking for Passwords
Sometimes, we would like to allow all users with sudo privilege to be able to execute a program – dosomething.sh as root,
without asking for passwords. To achieve this we need to add the following line to the sudo
command configuration (additionally make sure the script has executable permissions.).
ALL ALL=(root) NOPASSWD: /path/to/dosomething.sh
Now, all users with sudo
privilege can run the script /path/to/dosomething.sh
as the superuser without providing passwords.
2. Executing ALL sudo commands without password unconditionally
Using visudo
or directly editing the sudoer file add the following line to sudo
command configuration ->
{USERNAME} ALL=(ALL) NOPASSWD:ALL
Where {USERNAME} is the user name of the user who will be executing the commands.
3. Better Solution – Allow specific commands to be executed without a password
It is never a good idea to grant full access to a user such that they can execute any command with administrative rights. Instead, it is better to first ascertain what commands are required by the user at a bare minimum and allow only those commands.
Using visudo or directly editing the
sudoer file add the following line to sudo
command configuration ->
{USERNAME} ALL = NOPASSWD: /bin/systemctl restart nginx.service
Where {USERNAME} is the user name of the user who will be executing the commands.
Now the user can run the systemctl command to restart Nginx without password prompt as root. However the user cannot run any other command as per the configuration
stated.