How to run from PHP a bash script under root user

How to run from PHP a bash script under root user (with all permissions) and not nobody user – php default user?

thats my output after sudo visudo:

Defaults        env_keep += "LINES COLUMNS"
Defaults        env_keep += "LSCOLORS"
Defaults        env_keep += "SSH_AUTH_SOCK"
Defaults        env_keep += "TZ"
Defaults        env_keep += "DISPLAY XAUTHORIZATION XAUTHORITY"
Defaults        env_keep += "EDITOR VISUAL"
Defaults        env_keep += "HOME MAIL"

#User privilege specification
root    ALL=(ALL) ALL
%admin  ALL=(ALL) ALL


# Uncomment to allow people in group wheel to run all commands
# %wheel        ALL=(ALL) ALL

# Same thing without a password
# %wheel        ALL=(ALL) NOPASSWD: ALL

# Samples
# %users  ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
# %users  localhost=/sbin/shutdown -h now

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can use sudo:

exec("sudo /your/script");

You should allow executing your script without password prompt. Run sudo visudo in console and add the following string to the end:

nobody ALL = NOPASSWD: /your/script

You must set up file mode properly to ensure that no one can modify this script and put dangerous contents into it (in root console):

chown root:root /your/script
chmod 755 /your/script

Solution 2

You can make a program which is set-uid root. This causes the program to always run as root. This doesn’t work with shell scripts, so you have to use a program which calls your script.

Solution 3

Under Linux you normally do this using sudo. Try to be as specific as possible, so not to give the script too many permissions.

For examples on how to use sudo: http://aplawrence.com/Basics/sudo.html

Solution 4

I would add a specific rule to allow this script to be called by nobody user, using sudo.

Solution 5

I recently published a project that allows PHP to obtain and interact with a real Bash shell (as user: apache/www-data or root if needed). Get it here: https://github.com/merlinthemagic/MTS

After downloading you would simply use the following code:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1  = $shell->exeCmd('/full/path/to/script.sh');

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply