PHP sudo in shell_exec

断了今生、忘了曾经 提交于 2019-11-27 12:56:38

You could use the latest SVN version of phpseclib, a pure PHP SSH implementation, to do this. eg.

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
$ssh->login('username', 'password');

$ssh->read('[prompt]');
$ssh->write("sudo command\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>

The problem isn't that your page is or isn't secure, the problem is that giving a php page the ability to run some sudo command would give it to all pages including any injected code on any insecure page on any site on the server.

That said, it might be best to make a wrapper script that does just the one job that needs doing, then give the http user access to just that ONE command as sudo

http  ALL=(ALL) NOPASSWD:/user/local/bin/your_wrapper_script.sh

Definitley not advised. However, you will want to look into editing the sudoers file and add the user php is running as a NOPASSWD for the command you need to run. This will only allow him to sudo that one command with out entering a password.

If you need more commands add more to it. Sudoers Configuration I know that forum/post is debian based but sudo is not strictly debian and that should help you out with the sudo configuration values that you need to put it.

I just Google'd for php sudo shell_exec and this came up as the #1 match:

http://www.php.net/manual/en/function.shell-exec.php#101440

ilya at linemedia dot ru 16-Dec-2010 04:36
sudo can be executed without storing pass in a file

system('echo "PASS" | sudo -u root -S COMMAND');
SamyOteroGlez
$aux=echo "admin-pass" | your command;
echo $aux;

/******************************* ************Example************* *******************************/

Run a Perl script named my_perl_script.pl:

$aux=echo "admin-pass" | sudo -u root -S perl /path-to-the-script/my-perl-script.pl;
echo $aux;

Best way to do it:

$descriptorSpec = array(
    0 => STDIN,
    1 => STDOUT,
    2 => STDERR,
);

if (posix_getuid() === 0) {
    echo "Root\n";
} else {
    echo "No root\n";
    $command = 'sudo ' . PHP_BINARY . ' ' . implode(' ', $_SERVER['argv']);

    $pipes = [];
    $process = proc_open($command, $descriptorSpec, $pipes);
    if (is_resource($process)) {
        proc_close($process);
    }
}

It runs the same command again, with sudo prefixed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!