Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to execute/run a shell script as root from a PHP script?

DZone's Guide to

How to execute/run a shell script as root from a PHP script?

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

I am working on a project where the some of the commands should be executed by root.
It's a webBuild Your Site Right Using  Powered by bixt.net software that uses Plesk to setup domains, aliases change quotas etc.

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
and/or

chown root:root somescript.php

 

execute: visudo
Add this line
apache ALL=NOPASSWD: ALL
Also comment out the following line otherwise you'd get "sudo: sorry, you must have a tty to run sudo"
Target value:
#Defaults    requiretty
Note: 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: 

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:

Published at DZone with permission of Svetoslav Marinov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}