php proc_open';su:必须从终端运行';


php proc_open 'su: must be run from a terminal'

我在个人Ubuntu服务器机器中有以下PHP代码:

$cmd="su testuser";$descriptorspec=数组(数组('pipe','r'),数组('pipe','w'),数组('pipe','w'));$pipes=array();$process=proc_open($cmd,$descriptorspec,$pipes);fwrite($pipes[0],'password''r');fclose($pipes[0]);$string=数组(stream_get_contents($pipes[1]),stream_get-contents($spipes[2]));proc_close($process);echo-exec("hoami")。"''n";print_r($string);

我从PHP得到的回应是:

www数据大堆([0]=>[1] =>su:必须从终端运行)

很明显,我想更改活动用户,但有什么方法可以从php做到这一点吗?

su命令只会在执行它的bash shell仍在运行时更改当前用户。即使您要执行$cmd='bash-c"sudo su testuser"'(将按预期执行),在执行proc_close之前,您也只能更改当前用户,因此exec('hoami')将始终为您提供最初启动php脚本的用户的用户名。但是,您可以使用粗体命令来执行bash shell,该shell将以testuser的身份执行,然后将命令管道传输到它。例如,如果您管道传输"whoami"而不是"nirvana3105''r",whoami应该返回"testuser"。希望能有所帮助。

尝试此代码(用您的密码替换密码):

<?php
    $cmd = "sudo -S su testuser";
    echo $cmd;
    $desc = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w'));
    $pipes = array();
    $process = proc_open($cmd, $desc, $pipes);
    fwrite($pipes[0], "password'n");
    fwrite($pipes[0], "whoami");
    fclose($pipes[0]);
    $string = array(stream_get_contents($pipes[1]), stream_get_contents($pipes[2]));
proc_close($process);
    print_r($string);
 ?>