8

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?

Apostle
  • 482
  • 2
  • 7
  • 23
Kenneth Vogt
  • 985
  • 4
  • 12
  • 28

2 Answers2

4

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • While it *also* matters that the user account must be authorized, that doesn't mean there isn't a best choice for the PHP function to use. Which is best? – Kenneth Vogt Aug 06 '11 at 23:26
  • @Kenneth Vogt `exec`, since it doesn't needlessly involve the shell and returns the result, or `passthru`, which directly outputs the result, but would require some modification of the original code. – phihag Aug 07 '11 at 10:00
3

What you really need to do is set your web server to run as a specific user (other than 'nobody' for example), or give that user permissions to what you want to execute.

See also: PHP shell_exec() and sudo: must be setuid root

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • This begs the question: How do you "set your web server to run as a specific user other than 'nobody'"? – Kenneth Vogt Aug 06 '11 at 23:23
  • @Kenneth Vogt, how should I know, you didn't specify which server you were using. If you are using Apache, check the `User` and `Group` configuration directives. (http://httpd.apache.org/docs/1.3/mod/core.html#user) If you can't get that working, the appropriate place to ask is ServerFault.com. – Brad Aug 06 '11 at 23:39