Ubuntu 的自动 UID 生成行为是什么?

con*_*lee 6 users user-management

我对生成新用户但未明确给出 UID 的情况感兴趣,让 Ubuntu 自动分配 UID。我知道默认情况下 Ubuntu 会生成 1000 以上的 UID,但我想了解有关 ubuntu 的 UID 生成策略的所有信息。

对这个问题的一个好的回答将澄清以下几点

  • 如果已经使用了以下两个 UID,该怎么办:1001、2001 - 下一个自动生成的 UID 是 1002 还是 2002?
  • 是否有最大 UID?如果某个帐户已经分配了最大 UID(但还有其他免费 UID),Ubuntu 会做什么?

wal*_*tor 7

/etc/adduser.conf

# FIRST_SYSTEM_[GU]ID to LAST_SYSTEM_[GU]ID inclusive is the range for UIDs
# for dynamically allocated administrative and system accounts/groups.
# Please note that system software, such as the users allocated by the base-passwd
# package, may assume that UIDs less than 100 are unallocated.
FIRST_SYSTEM_UID=100
LAST_SYSTEM_UID=999

FIRST_SYSTEM_GID=100
LAST_SYSTEM_GID=999

# FIRST_[GU]ID to LAST_[GU]ID inclusive is the range of UIDs of dynamically
# allocated user accounts/groups.
FIRST_UID=1000
LAST_UID=29999

FIRST_GID=1000
LAST_GID=29999
Run Code Online (Sandbox Code Playgroud)

并且,在$(type -p adduser)or处阅读 Perl 脚本/usr/sbin/adduser,我们发现这个函数:

 sub first_avail_uid {
    my ($min, $max) = @_;
    printf (gtx("Selecting UID from range %d to %d ...\n"),$min,$max) if ($verbose > 1);

    my $t = $min;
    while ($t <= $max) {
       return $t if (!defined(getpwuid($t)));
       $t++;
    }
    return -1; # nothing available
}
Run Code Online (Sandbox Code Playgroud)

这意味着:adduser选择 1000 到 29999 之间的第一个空闲 UID,否则失败。

正确答案:1002,它会选择一个免费的。

存在最大 UID,4294967295,因为UIDs 是 32 位字段,但adduser使用下限。

但是,也有/usr/sbin/useradd BEWARE adduser并且useradd很容易被误认为/错误输入。

man useradd 告诉我:

DESCRIPTION
   useradd is a low level utility for adding users. On Debian,  
    administrators should usually use adduser(8) instead.

...  

   -u, --uid UID
       The numerical value of the user's ID. This value must be unique,
       unless the -o option is used. The value must be non-negative. The
       default is to use the smallest ID value greater than or equal to
       UID_MIN and greater than every other user.

       See also the -r option and the UID_MAX description.

...  

CONFIGURATION
   The following configuration variables in /etc/login.defs change the
   behavior of this tool:

...  

   SYS_UID_MAX (number), SYS_UID_MIN (number)
       Range of user IDs used for the creation of system users by useradd
       or newusers.

       The default value for SYS_UID_MIN (resp.  SYS_UID_MAX) is 101
       (resp.  UID_MIN-1).

   UID_MAX (number), UID_MIN (number)
       Range of user IDs used for the creation of regular users by useradd
       or newusers.

       The default value for UID_MIN (resp.  UID_MAX) is 1000 (resp.
       60000).
Run Code Online (Sandbox Code Playgroud)

其中一个原因是我用adduser的,而不是useradd--encrypt-home选项adduser。然而,任何一个都可以通过编辑一堆文件、复制其他文件、创建目录等来替换,使用任何 UID 选择(为什么,在过去,我......)。adduser或没有什么神奇之处useradd

  • 提示:从联机帮助页复制时,请从 http://manpages.ubuntu.com 上的在线版本复制。那里的文本以非常适合 Stack Exchange 帖子的宽度包裹。当您从终端复制时,终端的宽度可能会使行太长或太短,不利于阅读。 (2认同)