如何使用 phpseclib 以 root 权限执行 运行 ubuntu 命令

how to run ubuntu command with root permission using phpseclib

我使用 phpseclib 从 php 调用 ssh 命令。

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

在下面的例子中一切正常(因为我不需要权限):

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

问题出现在下一个例子中:

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

我尝试使用 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#

似乎一切正常(我在root上),但是:

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

哪里有问题?提前致谢!

我使用了 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);
}

而且有效!

您需要将 httpd 进程 (apache,php) 添加到 root 用户 group.That 子进程可以 运行 具有 root 权限。