1

我在个人 Ubuntu Server 机器上有这个 PHP 代码:

    $cmd = 'su testuser';
    $descriptorspec = 数组(
        数组('管道','r'),
        数组('管道','w'),
        数组('管道','w')
    );
    $pipes = 数组();
    $process = proc_open($cmd, $descriptorspec, $pipes);
    fwrite($pipes[0], '密码\r');
    fclose($pipes[0]);
    $string = array(stream_get_contents($pipes[1]), stream_get_contents($pipes[2]));
    proc_close($进程);
    回声 exec('whoami') 。"\n";
    print_r($string);

我从 PHP 得到这个响应:

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

)

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

4

1 回答 1

1

su 命令只会在它正在执行的 bash shell 仍在运行时更改当前用户。即使您要执行 $cmd = 'bash -c "sudo su testuser"'(将按预期执行),您也只会更改当前用户,直到执行 proc_close,因此 exec('whoami') 将始终为您提供最初启动您的 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);
 ?>
于 2013-12-16T17:08:19.530 回答