Search code examples
phpsudophpseclib

how to run ubuntu command with root permission using phpseclib


I use phpseclib to calling ssh command from php.

$ip = 'ip_address';
$login = 'user';
$password = 'password';
$ssh = new SSH2($ip);
$ssh->login($login, $password);

In example below everything is ok (because I dont need permissions):

$command = 'ifconfig';
$result = $ssh->exec($command); // result = 'eth0 ..., eth1 etc.'

Problem occurs in the next example:

$command = 'ip addr flush dev eth1';
$result = $ssh->exec($command); // result = 'Failed to send flush request: Operation not permitted'

I tried to log in with sudo su:

$result = $ssh->read('$'); // result = '..... user@hostname:~$'
$result = $ssh->write("sudo su\n"); //result = true
$result = $ssh->read(':');  // result = 'sudo su\n [sudo] password for user:'
$result = $ssh->write($password."\n"); // result = true
$result = $ssh->read('#'); //result = 'root@hostname:/home/user#

It seems that everything is okay (I'm on root), but:

$command = 'ip addr flush dev eth1';
$result = $ssh->exec($command);  // result = 'Failed to send flush request: Operation not permitted'

Where is a problem? Thank you in advance!


Solution

  • i used the following code from http://mrbluecoat.blogspot.com/2014/03/running-sudo-commands-with-phpseclib.html:

    $ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
    $ssh->write("sudo YOUR COMMAND HERE\n");
    $ssh->setTimeout(10);
    $output = $ssh->read('/.*@.*[$|#]|.*[pP]assword.*/', NET_SSH2_READ_REGEX);
    if (preg_match('/.*[pP]assword.*/', $output)) {
        $ssh->write($sudo_password."\n");
        $ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
    }
    

    and it works!