How to execute/run a shell script as root from a PHP script?
Join the DZone community and get the full member experience.Join For Free
I am working on a project where the some of the commands should be executed by root.
Because this setup is done on a testing/staging server I decided to enable Apache to execute scripts with root permissions.
That way the software I am working on would be better tested and would produce less bugs on production.
On production server I have a separate process which runs as root on a regular basis via cron.
So how to enable Apache web server execute other scripts as root ?
Login as root
Change the script's owner to be root
chown root:root somescript.php
Add this line
apache ALL=NOPASSWD: ALLAlso comment out the following line otherwise you'd get "sudo: sorry, you must have a tty to run sudo"
#Defaults requirettyNote: Ubuntu runs the apache web server under 'www-data' user so you may have to replace 'apache' with 'www-data'
By now you should be able to do:
<?php echo `sudo whoami`; ?>
You should see 'root'
Potential errors you may receive
sudo: sorry, you must have a tty to run sudo
We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things: #1) Respect the privacy of others. #2) Think before you type. #3) With great power comes great responsibility. Password:
Published at DZone with permission of Svetoslav Marinov, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.