php 如何从php脚本执行shell命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6685889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:59:47  来源:igfitidea点击:

How to execute a shell command from a php script

phpshell-exec

提问by Kenneth Vogt

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 脚本来执行 shell 命令并返回其输出。服务器需要私钥。当我第一次决定测试这个时,我创建了这个:

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

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

那工作得很好。但是当我更改$command为命令时,我真的很想运行:

$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 $commandbe? Should I use shell_exec(), exec(), system()or something else?

我的猜测是我需要使用sudo. 当然,这需要将 pem 文件放在服务器上的某个位置。假设我这样做,究竟应该$command是什么?我应该使用shell_exec()exec()system()或其他什么东西?

采纳答案by phihag

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

您使用哪个 php 函数来启动脚本并不重要 - 缺少的是您的用户帐户的授权。

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.

要么使用 sudo(预先配置 Web 服务器用户以通过 运行没有密码的确切命令visudo,并在命令前加上sudo)或设置一个 setuid 脚本来执行该命令。

回答by Brad

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.

您真正需要做的是将您的 Web 服务器设置为以特定用户身份运行(例如,“nobody”除外),或者为该用户授予您要执行的权限。

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

另请参阅: PHP shell_exec() 和 sudo:必须是 setuid root