Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a shell command from a php script

Tags:

php

shell-exec

I would like to create a php script to execute a shell command and return its output. The server requires a private key. When I first decided to test this out I created this:

<?php
$command = "ls";
$output = shell_exec($command);
echo "<pre>$output</pre>";
?>

That worked just fine. But when I changed $command to the command I really wanted to run:

$command = "/etc/init.d/mycontrollerd status /etc/mycontrollerconfig";

it gave me this output:

You need root privileges to run this script

My guess is I need to use sudo. Of course that will require putting the pem file somewhere on the server. Assuming I do that, what exactly should $command be? Should I use shell_exec(), exec(), system() or something else?

like image 363
Kenneth Vogt Avatar asked Jul 13 '11 21:07

Kenneth Vogt


1 Answers

It does not matter which php function you use to start the script - what lacks is the authorization of your user account.

Either use sudo (preconfigure the web server user to run the exact command without password via visudo, and prefix the command with sudo) or set up a setuid script that executes the command on itself.

like image 179
phihag Avatar answered Oct 14 '22 19:10

phihag