【问题标题】:how to run ubuntu command with root permission using phpseclib如何使用 phpseclib 以 root 权限运行 ubuntu 命令
【发布时间】:2016-07-26 19:02:23
【问题描述】:

我使用 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'

哪里出了问题?提前谢谢!

【问题讨论】:

  • 尝试将自己添加到 sudoers 文件中,然后只需键入 sudo 后跟命令(您不需要插入密码)
  • su 已经是一个 suid 二进制文件。无需运行它sudo,因为它始终以 root 身份运行。
  • 我在终端尝试过这样的事情:adduser user sudo,结果是:The user 'user' is already a member of 'sudo'。接下来我在终端中只使用了su,结果是:Password: su: Authentication failure
  • 这是 ubuntu 版本 16.04 LTS,现在我有 root 密码 (sudo passwd root),将尝试仅使用 su 的 phpseclib
  • 效果不好

标签: php sudo phpseclib


【解决方案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);
}

它有效!

【讨论】:

  • 不需要$ssh->setTimeout(10)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2011-03-01
    • 2011-12-22
    • 2016-11-23
    • 1970-01-01
    • 2014-12-29
    • 2019-10-15
    • 1970-01-01
    • 2010-09-28
    相关资源
    最近更新 更多