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

时间:2016-07-26 19:02:23

标签: php sudo 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#

似乎一切都还好(我在根上),但是:

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

哪里有问题?提前谢谢!

2 个答案:

答案 0 :(得分:1)

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

它有效!

答案 1 :(得分:0)

您需要将httpd进程(apache,php)添加到root用户组。辅助进程可以使用root perm运行。