我试图从PHP运行一个命令到我的Linux服务器,但是有一个命令遇到了一些问题:这是脚本:
<?php
$output=null;
$retval=null;
exec('speedtest -L -f, --format=json 2>&1', $output, $retval);
echo "Returned with status $retval and output:\n";
print_r($output);
?>产出如下:
Returned with status 134 and output:
Array ( [0] => terminate called after throwing an instance of 'std::logic_error'
[1] => what(): basic_string::_M_construct null not valid
[2] => Aborted (core dumped))运行脚本的用户是: www-data,如果我试图直接在终端上运行它,它就能工作。
command from terminal: sudo -u www-data speedtest -L
output: {"type":"serverList","timestamp":"2021-02-23T09:20:51Z","servers":[{"id":4302,"name":"Vodafone IT","location":"Milan","country":"Italy","host":"speedtest.vodafone.it","port":8080},{"id":7839,"name":"Fastweb SpA","location":"Milan","country":"Italy","host":"spd-pub-mi-01-01.fastwebnet.it","port":8080},{"id":11427,"name":"EOLO","location":"Milan","country":"Italy","host":"test.eolo.it","port":8080},{"id":1434,"name":"CWNET","location":"Milan","country":"Italy","host":"speedtest.cheapnet.it","port":8080},{"id":3667,"name":"TIM SpA","location":"Milan","country":"Italy","host":"speedtestmi1.telecomitalia.it","port":8080},{"id":8211,"name":"CDLAN S.R.L.","location":"Milan","country":"Italy","host":"speedtest.cdlan.it","port":8080},{"id":11675,"name":"Italiaonline Supernap","location":"Milan","country":"Italy","host":"speedtest-supernap.italiaonline.it","port":8080},{"id":20551,"name":"Optima Italia","location":"Milan","country":"Italy","host":"mi-speedtest.optimaitalia.com","port":8080},{"id":26415,"name":"P-Lab","location":"Milan","country":"Italy","host":"speed.speedymilan.net","port":8080},{"id":19177,"name":"Seeweb","location":"Milan","country":"Italy","host":"ookla-mil.seeweb.it","port":8080}]}如果我运行另一个命令,它将完美地工作:
<?php
$output=null;
$retval=null;
exec('whoami', $output, $retval);
sleep(1);
echo "Returned with status $retval and output:\n";
print_r($output);
?>产出如下:
Returned with status 0 and output: Array ( [0] => www-data )你们有什么建议吗?
发布于 2021-02-25 13:27:00
我想出了一个办法让它发挥作用,但可能不是最好的方法:
<?php
// attributes
private $output;
private $retval;
private $command;
// methods
function get_serverUpdates($user, $password) {
$command = 'echo '.$password.' | su -l '.$user.'-s /bin/bash -c "speedtest -L -f, --format=json" 2>&1';
$resl = exec($command, $output, $retval);
return json_decode(substr($resl, 10));
}
?>它确实返回正确的信息。
我认为问题在于,正如@MarkusZeller所说,www-data没有运行所有已安装程序的权限。
https://stackoverflow.com/questions/66330903
复制相似问题