I discovered that there are many different ways to run a program as root.

The most well known way is to use the sudo command

$> sudo run_as_root_program.sh

This, of course, prompts for the password which you need to then enter.

But what if we need to run the program itself from another program so that the password prompt doesn’t appear?

I came across this requirement recently and it took quite a few iterations before I got it right.

Run the calling program with sudo

If I have a program ‘meta_program.sh‘ which in turn calls the ‘run_as_root_program.sh‘ above, then if the ‘meta_program.sh‘ is run with sudo and the password prompt entered, then the ‘run_as_root_program.sh‘ doesn’t ask for the password anymore.

$> sudo meta_program.sh

But this means that this program in turn needs the prompt for the password!

Enter the sudo password on the command line

This was new to me! You can enter the password at the prompt itself! For example, if the password is ‘complexpass‘ then it is possible to run this command

$> echo complexpass | sudo -S ls /root

Reference: Stackoverflow

Of course, in terms of security, this is always a no-no as then anybody can then read the password from the .bash_history file.

So, there are ways to have commands to be skipped from the .bash_history file as well. One of them being to prefix the command with a space as long as this is set up in your .bashrc

HISTCONTROL=ignoreboth

So now, I thought I’d do this for the program and instead of calling it directly, we call it using this command instead.

 echo complexpass | sudo -S ls /root

Note the leading space.

Unfortunately, this works perfectly from the command prompt but not from within a program!

The reason being that when a program is running, then inside it, there’s no concept of a tty and hence the echo doesn’t work!

Give permission for sudo user to run a specific program as root without a prompt

This was new to me as well! It is possible to give specific sudo users the permissions to run specific files without the sudo command.

This is done by adding the corresponding details at the end of the /etc/sudoers file.

<user name> ALL=NOPASSWD: <full path to program>

So, for example, if the logged in user is ‘john‘ and the program is ‘run_as_root_program.sh‘ which is in the user’s home directory, the command becomes –

john ALL=NOPASSWD: /home/john/run_as_root_program.sh

Of all the options, when it comes to running a program in user mode which will issue system commands with root permissions, and when password prompt is to be avoided, option 3 works out best.