How to execute a shell command from a php script

痞子三分冷 提交于 2019-12-09 03:05:01

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6685889/how-to-execute-a-shell-command-from-a-php-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!