1

個人のUbuntuサーバーマシンに次のPHPコードがあります。

    $cmd = 'su testuser';
    $descriptorspec = 配列(
        array('パイプ', 'r'),
        array('パイプ', 'w'),
        array('パイプ', 'w')
    );
    $パイプ = 配列();
    $process = proc_open($cmd, $descriptorspec, $pipes);
    fwrite($pipes[0], 'パスワード\r');
    fclose($パイプ[0]);
    $string = array(stream_get_contents($pipes[1]), stream_get_contents($pipes[2]));
    proc_close($プロセス);
    echo exec('whoami') . "\n";
    print_r($string);

そして、私はPHPからこの応答を得ます:

www-データ
配列
(
    [0] =>
    [1] => su: 端末から実行する必要があります

)

アクティブユーザーを変更したいのは明らかですが、phpからこれを行う方法はありますか?

4

1 に答える 1

1

su コマンドは、それが実行されていた bash シェルがまだ実行されている間のみ、現在のユーザーを変更します。$cmd = 'bash -c "sudo su testuser"' (意図したとおりに実行されます) を実行したとしても、proc_close を実行するまで現在のユーザーを変更するだけなので、exec('whoami') は常にPHP スクリプトを最初に起動したユーザーのユーザー名。ただし、太字のコマンドを使用して、testuser として実行される bash シェルを実行し、コマンドをパイプすることができます。たとえば、'nirvana3105\r' の代わりに 'whoami' をパイプすると、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 に答える