Shell – Execute Shell Script from PHP as Root User

apache-httpdPHPscriptingshellsudo

Need to execute the following line from PHP:

$res = shell_exec('sudo sh /home/nicklas/cronjobs/make_account.sh
username password');

The problem is nothing happens on execution. If i try to echo $res it comes out blank. I've tried using system() also, same result. I'm guessing it doesn't work because i need to run the scrip with root access, and the www-data user doesn't have that by default. I added the following line to /etc/sudoers in hope of getting access:

www-data ALL=(ALL:ALL) NOPASSWD:
/home/nicklas/cronjobs/make_account.sh

But no success. I've tried restarting apache inbetween, doesn't change anything.

Am i missing something?

Best Answer

For security reasons you should never try to execute something with the user www-data with more privileges than it naturally has. There was a reason why some times ago the Apache access was moved to www-data. If you need to do something on your machine as root - and changing passwords or creating accounts is this 'something' - you should build an interface. Let the php-script put something somewhere and scan this via scripts executed from root and handle it there. You could f.e. create a file containing the users to add in a directory where www-data has access, and then perform this via root-cronjob every 5 minutes (or less) and move the file to a done-folder with timestamp to have control over what is happening.

Related Question