Files
chill_notes/Linux/CentOS/CentOS用户管理.md
2026-04-21 20:28:53 +08:00

154 lines
2.2 KiB
Markdown
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CentOS 用户管理
## 用户配置文件
| 文件 | 说明 |
|------|------|
| `/etc/passwd` | 用户账号信息 |
| `/etc/shadow` | 用户密码(加密) |
| `/etc/group` | 用户组信息 |
| `/etc/gshadow` | 组密码(加密) |
---
## 查看用户
```bash
# 查看所有用户列表
cut -d : -f 1 /etc/passwd
# 查看可登录系统的用户
cat /etc/passwd | grep -v /sbin/nologin | cut -d : -f 1
# 查看当前登录用户
whoami
# 查看当前登录用户详细信息
who
# 查看用户操作记录需root权限
w
# 查看指定用户操作
w username
# 查看用户登录历史
last
# 查看所有用户最后登录
lastlog
```
---
## 创建用户
```bash
# 创建普通用户
useradd username
# 创建用户并指定家目录
useradd -m username
# 创建用户并指定UID
useradd -u 1500 username
# 创建用户并添加到指定组
useradd -g groupname username
# 创建用户并添加到多个组
useradd -G group1,group2 username
```
---
## 设置密码
```bash
# 设置当前用户密码
passwd
# 设置指定用户密码需root
passwd username
```
---
## 修改用户
```bash
# 修改用户名
usermod -l newname oldname
# 修改用户家目录
usermod -d /new/home username
# 修改用户所属组
usermod -g groupname username
# 添加用户到附加组
usermod -G groupname username
# 添加用户到多个组
usermod -G group1,group2 username
```
---
## 删除用户
```bash
# 删除用户(保留家目录)
userdel username
# 删除用户及家目录
userdel -r username
# 强制删除(即使用户已登录)
userdel -f username
```
---
## 用户组管理
```bash
# 创建组
groupadd groupname
# 删除组
groupdel groupname
# 查看用户所属组
groups username
# 修改组名
groupmod -n newname oldname
```
---
## 常用场景
```bash
# 1. 创建新用户并设置密码
useradd -m devuser
passwd devuser
# 2. 将用户添加到 sudo 组CentOS 中是 wheel
usermod -aG wheel devuser
# 3. 禁止用户登录保留用户但禁止Shell登录
usermod -s /sbin/nologin username
# 4. 锁定用户账号
usermod -L username
# 5. 解锁用户账号
usermod -U username
```
---
> 参考:[Linux 用户管理](https://www.cnblogs.com/todarcy/p/11079228.html)