Search code examples
phpapachesudosu

run command as root via php


I have a php script which contains su. when I run it in shell it ask for root password and works well. but now I want make an interface for it. as you know all command in php-apache runs as www-data user and this user doesn't have specified password or it's not in sudoers. so I can't use "echo pass | sudo -S ..." because I don't know what is www-data's password and It is not logical on every server set password for www-data or add it in sudoers+nopass, is it?

What solution can you suggest to solve this problem?

one of my commands:

su -c \"/usr/sbin/dmidecode -s baseboard-serial-number | tr \  \-\"

Solution

  • phpseclib should be best library choice as it does not requires any additional extensions.

    <?php
    include('Net/SSH2.php');
    
    $ssh = new Net_SSH2('example.com');
    if (!$ssh->login('user', 'pass')) {
        exit('Login Failed');
    }
    
    echo $ssh->exec('whoami');
    echo $ssh->exec('pwd');
    ?>
    

    Another alternative is libssh2, but it has to be compiled separately and is notoriously difficult to setup/use.