php - 在 www-data (apache2, php) 下启动 shell 进程

标签 php linux shell apache2

我需要使用一些参数从删除服务器上的 shell 启动 php 进程,所以我认为制作 REST API 应该是个好主意,它在用户执行 GET 请求时执行一些功能。

我写了一个简单的 bash 脚本用于测试,并发现在从网站调用此脚本时未指定命令行参数:

shell_exec('/var/www/test.sh 123')

Bash 脚本源:

#!/bin/sh
echo $1;

当从 root(或其他现有用户)调用此 bash 脚本时,它会正确显示它收到的参数。当我从网站(在 apache2 下的用户 www-data 下运行)调用此脚本时,它什么都不返回:

此外,如果我在 www-data 用户下的控制台中执行此 bash 脚本,它也不会返回任何内容:

su -c '/var/www/test.sh 123' www-data

我还尝试从 php 的不同用户启动进程(假设出于安全原因这将不起作用,但以防万一):

$result = system("su -c '/var/www/test.sh 123' sexyuser", $data);
// var_dump($result): string(0) ""
// var_dump($data): int(1)

那么,我应该给 www-data 用户什么权限才能在 php 下运行进程?

最佳答案

您应该让 php 运行脚本并处理结果

检查 php.net on exec 例如 http://www.php.net/manual/en/function.exec.php

//called by example.com/myshell.php?day=today&k=y&whatever=youwant
$arguments = implode(" ", $_GET);
$lastline_of_exec_result = exec ( "/your/command.sh ".$arguments); //sh called with today y youwant
echo $lastline_of_exec;

其中 $arguments 是您的脚本从 GET 参数获得的所有信息的字符串化列表

如果你想要一个精确的矿石输入和输出,试试这个:

//called by example.com/myshell.php?day=today&k=y&whatever=youwant
$argument = $_GET['whatever'];
$output = array();
$last_line = exec("your/command.sh ".$argument, &$output); //sh called with youwant
foreach($output as $line)
    echo $line."<br/>".PHP_EOL;

或者当然(使用 shell_exec)

$argument = $_GET['whatever'];
$output = shell_exec("your/command.sh ".$argument);
echo "<pre>".$output."</pre>";

确保 (shell_)exec 没有在您的 php.ini 中的 disable_functions 下列出

关于php - 在 www-data (apache2, php) 下启动 shell 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14788010/

相关文章:

php - PHP 内存泄漏的常见原因是什么?

php - 如何为路由组中的所有请求设置 header

bash - 当 POSIX 规范说有必要避免歧义时,它是什么意思?

bash - 从脚本执行 SBT 命令

javascript - 如何强制选中表单的复选框?

php - 多个查询中 undefined offset

linux - Centos apache Web 服务器抛出 403 错误

linux - 从包含另一个文件中存在的关键字的文件中提取行

linux - 如何在 Linux 上的 Win7 VM 中使用多播?

arrays - 在 bash 中将一行(包含字符串和整数)转换为整数数组