如何创建一些 shell 命令的 API,并允许通过 PHP 访问它们?

How to create an API of some shell commands, and allow access to them via PHP?

我想在我的服务器上执行一些需要 root shell 访问权限的任务。我想制作一个可以从 PHP 访问的简单 API。

我想实现的事情是:

我已经为这两项任务编写了 bash 脚本。

我不想授予 PHP 对服务器的完全 root 访问权限,因为那太疯狂了,而是:

我怎样才能使指定的 bash-脚本从一个 linux-用户的 public_html 目录中的 PHP-文件可执行?

或者: 我怎样才能让 root shell 访问(通过 shell_exec)服务器上一个指定的 PHP 文件。

收到 arkascha 的有用评论后,我研究了 sudo 并发现 Ezequiel Hdez 在 sudo in php exec() 中的回答有助于找到我的问题的答案:

通过添加 sudoers file 允许 myuser sudo 我的 shell 脚本(通过键入 visudo 访问它):

myuser ALL = NOPASSWD: /path/to/myscript.sh

使脚本可执行:

chown u+x /path/to/myscript.sh

然后在PHP(来自"myuser")

exec("sudo /path/to/myscript.sh argument1 argument2"); 

现在我可以通过 PHP 做任何我想做的事,但只能通过 /path/to/myscript.sh

您可以使用这个项目:Github。它允许 PHP 获取真正的 Bash shell 并与真正的 Bash shell 交互,即使在没有 运行 网络服务器作为 root 的情况下也是如此。

在 composer/downloading 之后,您只需使用以下代码:

//read the documentation: here you get a root shell if you allowed sudo
$shellObj    = \MTS\Factories::getDevices()->getLocalHost()->getShell("bash", true);

//OR if you did not want to give the webserver sudo access, then you can use this syntax:
$shellObj       = \MTS\Factories::getDevices()->getLocalHost()->getShell("bash", false);
\MTS\Factories::getActions()->getRemoteUsers()->changeUser($shellObj, 'root', 'rootPassword');

//In both cases you now have a shell as root. This really is a bash shell, its not just wrapping the PHP shell functions.

//All you have left is to issue commands just like you would on a bash prompt
$strCmd = "mysqldump -h localhost -u SOURCE_USER -pSOURCEPASSWD SOURCE_DB | mysql -h localhost -u DEST_USER -pDEST_PASS DEST_DB";

//for the vast majority of commands that finish within 10 sec you need only issue the command
$return  = $shellObj->exeCmd($strCmd);
echo $return;// return from your command

//However if your command runs for more than 10 sec, you must set a timeout. e.g.
//timeout in miliseconds
$timeout = 20000;
$return  = $shellObj->exeCmd($strCmd, null, $timeout);
echo $return;// return from your command

随时对 $shellObj 发出更多命令,它 bash shell 已准备好接受命令,正如我所说,已准备好文档。