我需要从带有一些参数的remove服务器上的shell启动php进程,所以我认为制作REST API应该是个好主意,它在用户执行GET请求时执行一些功能。
我写了一个简单的bash脚本进行测试,并发现在从网站调用这个脚本时没有指定命令行参数:
shell_exec('/var/www/test.sh 123')
Bash脚本来源:
#!/bin/sh
echo $1;
当从root(或其他现有用户)调用这个bash脚本时,它会正确地显示它收到的参数。当我从网站(在apache2下的用户www数据下运行)调用这个脚本时,它什么都不返回:
此外,如果我在www数据用户下的控制台中执行这个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数据用户什么权限在php下运行进程呢?
您应该让php运行脚本并处理结果
例如,在exec上查看php.nethttp://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 arguments 获得的所有信息的字符串列表
如果你想要一个更精确的输入和输出,试试这个:
//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>";
确保php.ini 中的disable_functions
下没有列出(shell_)exec