其他选项

到目前为止,我们已经介绍了在 Linux 中创建本地用户帐户的最简单方法,但是“useradd”命令为我们提供了许多其他有用的选项。

添加到组

运行 useradd 命令时,我们可以使用 -g 或者 -G 标志将用户帐户添加到组中。
-g 标志将更改用户的主要组 ID (GID),默认情况下将创建与用户名相同的组 ID。
另一方面,-G 标志通常更有用,它允许我们指定用户帐户应该是其成员的补充组列表。

[jack@onitroad ~]# groupadd testgroup1
[jack@onitroad ~]# groupadd testgroup2
[jack@onitroad ~]# useradd testaccount -G testgroup1,testgroup2

在此示例中,我们首先使用“groupadd”创建两个名为 testgroup1 和 testgroup2 的组,我们要添加用户的组需要先存在。
创建两个组后,我们创建“testaccount”用户并将其作为成员添加到这两个组中。
将用户添加到任何补充组时,将修改 /etc/group 文件以反映这一点。

[jack@onitroad ~]# grep testgroup /etc/group
testgroup1:x:1002:testaccount
testgroup2:x:1003:testaccount

有关更多信息,请参阅我们关于在 Linux 中将用户帐户添加到组的帖子。

定义shell

在大多数 Linux 发行版中,当使用“useradd”命令创建帐户时,将设置 /bin/bash 的默认 shell。
但是,这可能会因发行版而异,因此我们可以使用 -s 标志显式设置 shell,如下所示。

[jack@onitroad ~]# useradd testaccount -s /sbin/nologin
[jack@onitroad ~]# grep testaccount /etc/passwd
testaccount:x:1001:1001::/home/testaccount:/sbin/nologin

这只是更新 /etc/passwd 文件中的 shell 字段。
/sbin/nologin shell 本质上拒绝帐户登录系统,因为它没有定义 shell。

账户到期

默认情况下,当创建用户帐户时,密码永远不会过期,这是一种不好的安全做法,我们可以定义帐户何时过期并要求使用 -e 选项更改密码,然后是帐户的过期日期YYYY-MM-DD 的格式

[jack@onitroad ~]# useradd testaccount -e 2015-11-30

指定用户 ID (UID)

使用“useradd”时,UID 会自动设置为下一个可用数字,但是我们可以使用 -u 选项显式设置当前未使用的用户 ID。

[jack@onitroad ~]# useradd testaccount -u 1337
[jack@onitroad ~]# id testaccount
uid=1337(testaccount) gid=1337(testaccount) groups=1337(testaccount)

请注意,通过将 UID 设置为特定值,即使我们有较低的可用值,我们创建的下一个用户帐户也将从该值递增。

注释

/etc/passwd 文件中有一个字段允许放置注释。

[jack@onitroad ~]# useradd testaccount -c "comment"
[jack@onitroad ~]# grep testaccount /etc/passwd
testaccount:x:1339:1339:comment:/home/testaccount:/bin/bash
Linux 如何添加用户帐户

在 Linux 中,我们可以使用“useradd”命令创建一个新用户帐户。
在这里,我们将介绍将各种语法选项与 useradd 结合使用以在 Linux 中创建新的本地用户帐户的一些示例。

创建本地用户帐户

这是在 Linux 中创建本地用户帐户的最基本示例,在这种情况下,我们运行 useradd 命令并指定我们要创建的用户名,即“testaccount”。

[jack@onitroad ~]# useradd testaccount

本质上,这会将所需的配置行写入 /etc/passwd 文件,如下所示。

[jack@onitroad ~]# grep testaccount /etc/passwd
testaccount:x:1001:1001::/home/testaccount:/bin/bash

此时用户账号没有设置密码,所以默认禁用,无法使用。
我们可以使用“passwd”命令设置密码,然后是用户帐户。

[jack@onitroad ~]# passwd testaccount
Changing password for user testaccount.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

设置密码后,包含散列密码的配置将写入 /etc/shadow 文件。

[jack@onitroad ~]# grep testaccount /etc/shadow
testaccount:$qZu9sWPN$/lN1U3qmpZ7xFKNACkEhu1:16968:0:99999:7:::
日期:2020-07-07 20:56:08 来源:oir作者:oir