检查用户是否为root

问题描述:

如何验证用户是否是PHP脚本的root用户?命令是什么? 我尝试过类似的东西:

How can i verify if a user is root in a PHP script ? What is the command ? I tried something like that :

exec("su -l login < `echo password`");

但是su命令无法接收密码...

but the su command can not receive password...

请注意,该计算机与Internet隔离,因此如果需要,我可以以root用户身份运行PHP.

Note that the machine is isolated from internet so I can run PHP as root if needed.

我不想知道运行脚本的当前用户是否为root. 我在PHP脚本中有一个用户列表,我想为每个登录名是否拥有root特权.

I don't want to know if the current user who run the script is root or not. I have a list of users in my PHP script and I want to know for each login if he has root privileges.

首先,问问自己到底是什么定义了具有root特权"的登录名. AFAICT有2种基本解决方案.

First, ask yourself what exactly defines a login "having root privileges". AFAICT there are 2 basic solutions.

系统管理员使用uid 0创建多个帐户的传统方法,我-我当然并不孤单-认为这是一场噩梦.在这种情况下,您可以使用 posix_getpwnam 检查列表中的所有用户并查看其uid是否匹配0.

The old-school way, where sysadmins create multiple accounts with uid 0, which I - and I'm certainly not alone in this - consider to be a nightmare. In this scenario you could check all users in your list using posix_getpwnam and see if their uid matches 0.

以下代码段就是这样做的,$ privileged将包含具有root特权的用户:

The following code snippet does just that, $privileged will contain the users with root privileges :

$logins = array('root', 'john', 'guest', 'foo');
$privileged = array();
foreach($logins as $login) {
    $userInfo = posix_getpwnam($login);
    if ($userInfo !== FALSE) {
        if ($userInfo['uid'] == 0) {
          $privileged[] = $login;
        }
    }
}

另一种方法(也是唯一一种理智的方法)是将具有root/管理特权的所有用户添加到特定组(已经使用 wheel admin 在不同的Linux发行版中,找出适合您的一种).这种情况甚至更简单,因为您可以使用 posix_getgrnam 来获取特定组中的所有成员.

The other (and imho only sane) way to do this is to add all users with root/administrative privileges to a specific group (wheel or admin are already used in different Linux distributions, find out which one works for you). This scenario is even simpler, since you can use posix_getgrnam to fetch all members in a specific group.

以下代码段将与您提供的登录名数组匹配,并查看谁是具有特定特权的成员,再次$ privileged将包含结果(即,列表中的用户是您指定的组的成员) :

The following code snippet will match an array of logins you provide, and see who's a member with specific privileges, again $privileged will contain the result (ie. the users in your list that are a member of the group you specified) :

$logins = array('root', 'john', 'guest', 'foo');
$privileged = array();
$groupInfo = posix_getgrnam('admins');
if ($groupInfo !== FALSE) {
    $privileged = array_intersect($logins, $groupInfo['members']);
}