How to run a specific program as root without a password prompt?
If there are multiple matching entries in /etc/sudoers
, sudo uses the last one. Therefore, if you can execute any command with a password prompt, and you want to be able to execute a particular command without a password prompt, you need the exception last.
myusername ALL = (ALL) ALL
myusername ALL = (root) NOPASSWD: /path/to/my/program
Note the use of (root)
, to allow the program to be run as root but not as other users. (Don't give more permissions than the minimum required unless you've thought out the implications.)
Note for readers who aren't running Ubuntu or who have changed the default sudo configuration (Ubuntu's sudo is ok by default): Running shell scripts with elevated privileges is risky, you need to start from a clean environment (once the shell has started, it's too late (see Allow setuid on shell scripts), so you need sudo to take care of that). Make sure that you have Defaults env_reset
in /etc/sudoers
or that this option is the compile-time default (sudo sudo -V | grep env
should include Reset the environment to a default set of variables
).
You have another entry in the sudoers
file, typically located at /etc/sudoers
, which also matches your user. The NOPASSWD
rule needs to be after that one in order for it to take precedence.
Having done that, sudo
will prompt for a password normally for all commands except /path/to/my/program
, which it will always let you run without asking for your password.
WARNING: This answer has been deemed insecure. See comments below
Complete Solution: The following steps will help you achieve the desired output:
Create a new script file (replace
create_dir.sh
with your desired script name):vim ~/create_dir.sh
The script will be created in the user’s home directory
Add some commands that only a
root
orsudo
user can execute like creating a folder at the root directory level:mkdir /abc
Note: Don’t add
sudo
to these commands. Save and exit (using:wq!
)Assign execute permissions to it using:
sudo chmod u+x create_dir.sh
Make changes so that this script doesn’t require a password.
Open the
sudoers
file:sudo visudo -f /etc/sudoers
Add the following line at the end:
ahmad ALL=(root) NOPASSWD: /home/ahmad/create_dir.sh
Replace
ahmad
with whatever your username is. Also make sure this is the last line. Save and exit.
Now when running the command add
sudo
before it like:sudo ./create_dir.sh
This will run the commands inside the script file without asking for a password.
Follow the easy steps mentioned here http://step4wd.com/2013/09/14/run-root-commands-in-linux-ubuntu-without-password/