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.
You can use sudo:
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
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.
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
I would add a specific rule to allow this script to be called by
nobody user, using
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 🙂