【问题标题】:Execute command with sudo via PHP通过 PHP 使用 sudo 执行命令
【发布时间】:2016-06-07 18:23:28
【问题描述】:

我在/etc/init.d/ 中有用于控制游戏服务器的脚本,我想构建一个简单的 Web 界面来调用这些脚本。我的 sudoers 文件包含类似

www-data ALL=(ALL) NOPASSWD: /etc/init.d/starbound start stop

当我在 PHP 中执行 sudo /etc/init.d/starbound start 时,什么也没有发生。我错过了什么吗?尝试访问不允许我的 PHP 用户访问的路径通常至少会给我适当的警告。

【问题讨论】:

  • 尝试使用sudo 可执行文件的绝对路径。
  • ^ 如果您不确定 sudo 的完整路径,可以使用 which sudo 找到它。
  • 不,没用。我还检查了所需的文件是否可以访问,is_executable("/usr/bin/sudo");trueis_executable("/etc/init.d/starbound");
  • 应该查看 auth.log,内容为:Jun 7 20:33:11 smares sudo: pam_unix(sudo:auth): conversation failed Jun 7 20:33:11 smares sudo: pam_unix(sudo:auth): auth could not identify password for [www-data] Jun 7 20:33:11 smares sudo: www-data : command not allowed ; TTY=unknown ; PWD=/var/www/smares.de/ajax ; USER=root ; COMMAND=/etc/init.d/starbound start

标签: php sudo


【解决方案1】:

使用sudo 要求您在运行命令时输入密码。通过使用exec() 运行sudo,您没有提供sudo 的密码,并且无法以root 级权限运行该命令。

Ubuntu.SE provides a way to pass the password to sudo in a single command,但使用 PHP 实现时结果有点混乱,因为在进行调用时,Password: 提示将被发送到 STDOUT,但可以通过将输出发送到 /dev/null 来消除这种情况。该命令的结果仍然可以像您所期望的那样存储在变量中。

<?php
//Kill a sudo session if one exists.
exec('sudo -k');

//Run sudo without authenticating
$output = exec('sudo echo "foo"');
var_dump($output); //string(0) ""

//Provide the password and pipe it into sudo.
$output = exec('echo "password" | sudo -S echo "foo" 2> /dev/null');
var_dump($output); //string(3) "foo"
?>

【讨论】:

  • 如果为相应的命令指定 NOPASSWD,则不必输入密码。现在可以了。我的错误是我认为在命令之后,我可以指定一个空白分隔的允许参数列表,例如start stop。但是,这不是一个列表,而是预期的确切参数,所以我必须指定 /path/to/executable start, /path/to/executable stop
  • @smares,有趣!我不知道 - 很高兴听到你找到了解决方案。我将在此处保留此答案,因为我认为它适用于未来的搜索者,我找不到与您的标题相似的问题。
【解决方案2】:

似乎问题出在 sudoers 文件中。如果我删除start stop,它会起作用。

所以正确的 sudoers 可能如下所示:

Cmnd_Alias GAMES = /etc/init.d/ark_thecenter start, \
                   /etc/init.d/ark_thecenter stop, \
                   /etc/init.d/ark_theisland start, \
                   /etc/init.d/ark_theisland stop, \
                   /etc/init.d/starbound start, \
                   /etc/init.d/starbound stop

www-data ALL=(ALL) NOPASSWD: GAMES

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多