# 用户组和用户管理

## groupadd 命令

`groupadd` 命令:

介绍：创建用户组

格式：useradd \[option] groupname

用法：

* groupadd groupname 创建组
* -g ：指定gid(一般从500开始)，再增加后从上次组gid开始

```bash
[root@localhost ~]# groupadd test
[root@localhost ~]# tail -1 /etc/group
test:x:1001:
[root@localhost ~]# groupadd -g 501 test1
[root@localhost ~]# tail -2 /etc/group
test:x:1001:
test1:x:501:
```

## groupdel 命令

groupdel 命令：

介绍：删除用户组

格式：groupdel \[option] groupname

用法：

* groupname 删除组(要保证内用户为空)

```bash
[root@localhost ~]# groupdel test
[root@localhost ~]# groupdel test1
[root@localhost ~]# tail -5 /etc/group
postdrop:x:90:
postfix:x:89:
chrony:x:996:
ping:x:1000:
slocate:x:21:
[root@localhost ~]# groupdel ping
groupdel：不能移除用户“ping”的主组
```

## useradd 命令

useradd命令：

介绍：创建用户

格式：useradd \[option] username

用法：

* useradd username：创建用户
* -u uid ： 指定uid
* -g groupname|gid ：指定组名或gid
* -d /dir/  : 指定家目录
* -s   ：指定bash
* -M  ：不建立其家目录

```bash
[root@localhost ~]# useradd test
[root@localhost ~]# tail -1 /etc/passwd
test:x:1001:1001::/home/test:/bin/bash
[root@localhost ~]# useradd -u 1003 -g 1001 test1
[root@localhost ~]# tail -2 /etc/passwd
test:x:1001:1001::/home/test:/bin/bash
test1:x:1003:1001::/home/test1:/bin/bash
[root@localhost ~]# useradd -s /sbin/nologin -M test2
[root@localhost ~]# tail -3 /etc/passwd
test:x:1001:1001::/home/test:/bin/bash
test1:x:1003:1001::/home/test1:/bin/bash
test2:x:1004:1004::/home/test2:/sbin/nologin
[root@localhost ~]#
```

> -s 制定 /sbin/nologin 表示不允许用户登陆

还有一个查看用户的命令

## id 命令

`id` 命令:

介绍：查看用户及其uid、gid、组

格式：id \[uid|username]

用法：

* id ：直接使用查看当前用户信息
* id username|uid ：查看\
  指定用户信息

```bash
[root@localhost ~]# id
uid=0(root) gid=0(root) 组=0(root)
[root@localhost ~]# id 1001
uid=1001(test) gid=1001(test) 组=1001(test)
[root@localhost ~]# id test1
uid=1003(test1) gid=1001(test) 组=1001(test)
```

## userdel 命令

`userdel` 命令：

介绍：删除用户

格式：userdel \[option] username

用法：

* userdel username：删除用户
* -r ：同时删除家目录&#x20;

```bash
[root@localhost ~]# userdel test
userdel：没有删除 test 组，因为它是另外一个用户的主组。
[root@localhost ~]# tail -3 /etc/passwd
ping:x:1000:1000::/home/ping:/bin/bash
test1:x:1003:1001::/home/test1:/bin/bash
test2:x:1004:1004::/home/test2:/sbin/nologin
[root@localhost ~]# userdel -r test1
[root@localhost ~]# tail -3 /etc/passwd
chrony:x:998:996::/var/lib/chrony:/sbin/nologin
ping:x:1000:1000::/home/ping:/bin/bash
test2:x:1004:1004::/home/test2:/sbin/nologin
[root@localhost ~]# ls /home
ping  test
```
