我需要使用一些参数从删除服务器上的 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/