user-management

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

User Management

用户管理

Manage users, groups, permissions, sudo access, PAM modules, and LDAP integration on Linux systems. Includes practical scripts for bulk user operations and access auditing.
在Linux系统中管理用户、组、权限、sudo访问、PAM模块以及LDAP集成。包含用于批量用户操作和访问审计的实用脚本。

When to Use

适用场景

  • Creating and managing local user accounts on Linux servers
  • Configuring sudo access with fine-grained privilege controls
  • Setting up group-based access control for teams
  • Integrating Linux hosts with LDAP or Active Directory for centralized auth
  • Auditing user accounts, permissions, and access patterns
  • Automating bulk user provisioning and deprovisioning
  • 在Linux服务器上创建和管理本地用户账户
  • 配置具有细粒度权限控制的sudo访问
  • 为团队设置基于组的访问控制
  • 将Linux主机与LDAP或Active Directory集成以实现集中式认证
  • 审计用户账户、权限和访问模式
  • 自动化批量用户的创建和注销

Prerequisites

前置条件

  • Root or sudo access on the target system
  • shadow-utils
    package (provides useradd, usermod, etc.) -- installed by default
  • libpam-modules
    for PAM configuration
  • For LDAP:
    sssd
    ,
    realmd
    ,
    libpam-ldapd
    , or
    nslcd
    packages
  • For auditing:
    auditd
    package
  • 目标系统的Root或sudo访问权限
  • shadow-utils
    包(提供useradd、usermod等工具)——默认已安装
  • 用于PAM配置的
    libpam-modules
  • 若使用LDAP:需安装
    sssd
    realmd
    libpam-ldapd
    nslcd
  • 若使用审计功能:需安装
    auditd

User Operations

用户操作

Creating Users

创建用户

bash
undefined
bash
undefined

Create a user with home directory, default shell, and comment

Create a user with home directory, default shell, and comment

useradd -m -s /bin/bash -c "Jane Smith" jsmith
useradd -m -s /bin/bash -c "Jane Smith" jsmith

Set the user's password interactively

Set the user's password interactively

passwd jsmith
passwd jsmith

Create a user with a specific UID and primary group

Create a user with a specific UID and primary group

useradd -m -s /bin/bash -u 1500 -g developers -c "Deploy Account" deploy
useradd -m -s /bin/bash -u 1500 -g developers -c "Deploy Account" deploy

Create a system account (no home, no login shell) for running services

Create a system account (no home, no login shell) for running services

useradd -r -s /usr/sbin/nologin -d /opt/myapp -c "MyApp Service Account" myapp
useradd -r -s /usr/sbin/nologin -d /opt/myapp -c "MyApp Service Account" myapp

Create a user with an expiration date (contractor access)

Create a user with an expiration date (contractor access)

useradd -m -s /bin/bash -e 2025-12-31 -c "Contractor - Bob Lee" blee
useradd -m -s /bin/bash -e 2025-12-31 -c "Contractor - Bob Lee" blee

Create user and add to multiple supplementary groups at creation time

Create user and add to multiple supplementary groups at creation time

useradd -m -s /bin/bash -G docker,developers,ssh-users -c "Dev User" devuser
undefined
useradd -m -s /bin/bash -G docker,developers,ssh-users -c "Dev User" devuser
undefined

Modifying Users

修改用户

bash
undefined
bash
undefined

Add a user to a supplementary group (preserving existing groups with -a)

Add a user to a supplementary group (preserving existing groups with -a)

usermod -aG sudo jsmith usermod -aG docker,developers jsmith
usermod -aG sudo jsmith usermod -aG docker,developers jsmith

Change the user's login shell

Change the user's login shell

usermod -s /bin/zsh jsmith
usermod -s /bin/zsh jsmith

Change the user's home directory and move existing files

Change the user's home directory and move existing files

usermod -d /home/jsmith-new -m jsmith
usermod -d /home/jsmith-new -m jsmith

Lock a user account (disable login without deleting)

Lock a user account (disable login without deleting)

usermod -L jsmith
usermod -L jsmith

Unlock a user account

Unlock a user account

usermod -U jsmith
usermod -U jsmith

Set an account expiration date

Set an account expiration date

usermod -e 2025-06-30 blee
usermod -e 2025-06-30 blee

Change a user's login name

Change a user's login name

usermod -l jsmith-new jsmith
usermod -l jsmith-new jsmith

Force password change on next login

Force password change on next login

chage -d 0 jsmith
chage -d 0 jsmith

Set password aging: min 7 days, max 90 days, warn 14 days before

Set password aging: min 7 days, max 90 days, warn 14 days before

chage -m 7 -M 90 -W 14 jsmith
chage -m 7 -M 90 -W 14 jsmith

View password aging info

View password aging info

chage -l jsmith
undefined
chage -l jsmith
undefined

Deleting Users

删除用户

bash
undefined
bash
undefined

Remove a user and their home directory

Remove a user and their home directory

userdel -r jsmith
userdel -r jsmith

Remove a user but keep their home directory (for auditing)

Remove a user but keep their home directory (for auditing)

userdel jsmith
userdel jsmith

Find and reassign files owned by a deleted user (by UID)

Find and reassign files owned by a deleted user (by UID)

find / -uid 1500 -exec chown newowner:newgroup {} ;
undefined
find / -uid 1500 -exec chown newowner:newgroup {} ;
undefined

Group Management

组管理

bash
undefined
bash
undefined

Create a new group

Create a new group

groupadd developers
groupadd developers

Create a group with a specific GID

Create a group with a specific GID

groupadd -g 2000 devops
groupadd -g 2000 devops

Add a user to a group

Add a user to a group

usermod -aG developers jsmith
usermod -aG developers jsmith

Alternative using gpasswd

Alternative using gpasswd

gpasswd -a jsmith developers
gpasswd -a jsmith developers

Remove a user from a group

Remove a user from a group

gpasswd -d jsmith developers
gpasswd -d jsmith developers

Set group administrators (can add/remove members without root)

Set group administrators (can add/remove members without root)

gpasswd -A jsmith developers
gpasswd -A jsmith developers

Delete a group

Delete a group

groupdel developers
groupdel developers

List all groups a user belongs to

List all groups a user belongs to

groups jsmith id jsmith
groups jsmith id jsmith

List all members of a group

List all members of a group

getent group developers
getent group developers

Show all groups on the system

Show all groups on the system

cat /etc/group | cut -d: -f1 | sort
undefined
cat /etc/group | cut -d: -f1 | sort
undefined

Sudo Configuration

Sudo配置

bash
undefined
bash
undefined

Always edit sudoers via visudo (syntax validation prevents lockout)

Always edit sudoers via visudo (syntax validation prevents lockout)

visudo
visudo

Better: use drop-in files in /etc/sudoers.d/

Better: use drop-in files in /etc/sudoers.d/

visudo -f /etc/sudoers.d/developers
undefined
visudo -</think_never_used_51bce0c785ca2f68081bfa7d91973934>f /etc/sudoers.d/developers
undefined

/etc/sudoers.d/developers

/etc/sudoers.d/developers

text
undefined
text
undefined

Allow the developers group to restart specific services

Allow the developers group to restart specific services

%developers ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp, /usr/bin/systemctl status myapp
%developers ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp, /usr/bin/systemctl status myapp

Allow a deploy user full sudo with no password

Allow a deploy user full sudo with no password

deploy ALL=(ALL) NOPASSWD: ALL
deploy ALL=(ALL) NOPASSWD: ALL

Allow ops team to run docker commands only

Allow ops team to run docker commands only

%ops ALL=(ALL) NOPASSWD: /usr/bin/docker, /usr/bin/docker-compose
%ops ALL=(ALL) NOPASSWD: /usr/bin/docker, /usr/bin/docker-compose

Allow a user to run commands as a specific service account

Allow a user to run commands as a specific service account

jsmith ALL=(myapp) NOPASSWD: /opt/myapp/bin/*
jsmith ALL=(myapp) NOPASSWD: /opt/myapp/bin/*

Restrict to specific hosts (useful with centralized sudoers)

Restrict to specific hosts (useful with centralized sudoers)

jsmith dbservers=(root) /usr/bin/systemctl restart postgresql
jsmith dbservers=(root) /usr/bin/systemctl restart postgresql

Log all sudo commands to a dedicated file

Log all sudo commands to a dedicated file

Defaults log_output Defaults!/usr/bin/sudoreplay !log_output Defaults logfile="/var/log/sudo.log"
Defaults log_output Defaults!/usr/bin/sudoreplay !log_output Defaults logfile="/var/log/sudo.log"

Require password re-entry every 5 minutes (default is 15)

Require password re-entry every 5 minutes (default is 15)

Defaults timestamp_timeout=5
Defaults timestamp_timeout=5

Require password for sudo even if user has NOPASSWD elsewhere

Require password for sudo even if user has NOPASSWD elsewhere

Defaults:jsmith !authenticate

```bash
Defaults:jsmith !authenticate

```bash

Validate sudoers syntax without applying

Validate sudoers syntax without applying

visudo -c
visudo -c

Check what sudo permissions a user has

Check what sudo permissions a user has

sudo -l -U jsmith
sudo -l -U jsmith

Test a specific sudo command as a user

Test a specific sudo command as a user

sudo -u myapp /opt/myapp/bin/healthcheck.sh
undefined
sudo -u myapp /opt/myapp/bin/healthcheck.sh
undefined

File Permissions and ACLs

文件权限与ACL

bash
undefined
bash
undefined

Standard permissions

Standard permissions

chmod 755 /opt/myapp # rwxr-xr-x chmod 640 /etc/myapp.conf # rw-r----- chmod u+x script.sh # Add execute for owner chmod g+w shared-dir/ # Add write for group chmod o-rwx private-file # Remove all permissions for others
chmod 755 /opt/myapp # rwxr-xr-x chmod 640 /etc/myapp.conf # rw-r----- chmod u+x script.sh # Add execute for owner chmod g+w shared-dir/ # Add write for group chmod o-rwx private-file # Remove all permissions for others

Change ownership

Change ownership

chown deploy:developers /opt/myapp chown -R deploy:developers /opt/myapp/ # Recursive
chown deploy:developers /opt/myapp chown -R deploy:developers /opt/myapp/ # Recursive

Set the SGID bit (new files inherit group ownership)

Set the SGID bit (new files inherit group ownership)

chmod g+s /opt/shared/
chmod g+s /opt/shared/

Set the sticky bit (only owner can delete their files)

Set the sticky bit (only owner can delete their files)

chmod +t /tmp/shared/
chmod +t /tmp/shared/

Access Control Lists (ACLs) for fine-grained control

Access Control Lists (ACLs) for fine-grained control

Grant read-execute to a specific user on a directory

Grant read-execute to a specific user on a directory

setfacl -m u:jsmith:rx /opt/myapp/logs/
setfacl -m u:jsmith:rx /opt/myapp/logs/

Grant read-write to a group

Grant read-write to a group

setfacl -m g:developers:rw /opt/shared/
setfacl -m g:developers:rw /opt/shared/

Set default ACL (applied to new files created in the directory)

Set default ACL (applied to new files created in the directory)

setfacl -d -m g:developers:rw /opt/shared/
setfacl -d -m g:developers:rw /opt/shared/

View ACLs

View ACLs

getfacl /opt/shared/
getfacl /opt/shared/

Remove a specific ACL entry

Remove a specific ACL entry

setfacl -x u:jsmith /opt/myapp/logs/
setfacl -x u:jsmith /opt/myapp/logs/

Remove all ACLs

Remove all ACLs

setfacl -b /opt/shared/
undefined
setfacl -b /opt/shared/
undefined

PAM Configuration

PAM配置

bash
undefined
bash
undefined

PAM config files are in /etc/pam.d/

PAM config files are in /etc/pam.d/

Each file controls auth for a specific service (sshd, login, sudo, etc.)

Each file controls auth for a specific service (sshd, login, sudo, etc.)

Enforce password complexity via pam_pwquality

Enforce password complexity via pam_pwquality

/etc/pam.d/common-password (Debian) or /etc/pam.d/system-auth (RHEL)

/etc/pam.d/common-password (Debian) or /etc/pam.d/system-auth (RHEL)

password requisite pam_pwquality.so retry=3 minlen=12 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
password requisite pam_pwquality.so retry=3 minlen=12 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1

Configure /etc/security/pwquality.conf

Configure /etc/security/pwquality.conf

minlen = 12 dcredit = -1 ucredit = -1 ocredit = -1 lcredit = -1 maxrepeat = 3 dictcheck = 1
minlen = 12 dcredit = -1 ucredit = -1 ocredit = -1 lcredit = -1 maxrepeat = 3 dictcheck = 1

Limit concurrent logins per user

Limit concurrent logins per user

/etc/security/limits.conf

/etc/security/limits.conf

jsmith hard maxlogins 3 @developers hard maxlogins 5
jsmith hard maxlogins 3 @developers hard maxlogins 5

Lock account after 5 failed login attempts

Lock account after 5 failed login attempts

/etc/pam.d/common-auth (Debian)

/etc/pam.d/common-auth (Debian)

auth required pam_faillock.so preauth silent deny=5 unlock_time=900 auth required pam_faillock.so authfail deny=5 unlock_time=900
auth required pam_faillock.so preauth silent deny=5 unlock_time=900 auth required pam_faillock.so authfail deny=5 unlock_time=900

View failed login attempts

View failed login attempts

faillock --user jsmith
faillock --user jsmith

Unlock a locked account

Unlock a locked account

faillock --user jsmith --reset
undefined
faillock --user jsmith --reset
undefined

LDAP / Active Directory Integration

LDAP / Active Directory集成

bash
undefined
bash
undefined

Install SSSD and realmd for AD integration (Ubuntu/Debian)

Install SSSD and realmd for AD integration (Ubuntu/Debian)

apt install -y sssd realmd adcli sssd-tools libnss-sss libpam-sss
apt install -y sssd realmd adcli sssd-tools libnss-sss libpam-sss

Install SSSD and realmd (RHEL/CentOS)

Install SSSD and realmd (RHEL/CentOS)

dnf install -y sssd realmd adcli sssd-tools oddjob oddjob-mkhomedir
dnf install -y sssd realmd adcli sssd-tools oddjob oddjob-mkhomedir

Discover and join an Active Directory domain

Discover and join an Active Directory domain

realm discover corp.example.com realm join corp.example.com -U admin@CORP.EXAMPLE.COM
realm discover corp.example.com realm join corp.example.com -U admin@CORP.EXAMPLE.COM

Verify the join

Verify the join

realm list
realm list

Allow specific AD groups to log in

Allow specific AD groups to log in

realm permit -g "Linux Admins@corp.example.com" realm permit -g "Developers@corp.example.com"
realm permit -g "Linux Admins@corp.example.com" realm permit -g "Developers@corp.example.com"

Deny all except permitted groups

Deny all except permitted groups

realm deny --all realm permit -g "Linux Admins@corp.example.com"
realm deny --all realm permit -g "Linux Admins@corp.example.com"

Restart SSSD after config changes

Restart SSSD after config changes

systemctl restart sssd
systemctl restart sssd

Test LDAP user lookup

Test LDAP user lookup

id jsmith getent passwd jsmith
id jsmith getent passwd jsmith

Grant sudo to an AD group

Grant sudo to an AD group

echo '%linux\ admins ALL=(ALL) ALL' > /etc/sudoers.d/ad-admins
undefined
echo '%linux\ admins ALL=(ALL) ALL' > /etc/sudoers.d/ad-admins
undefined

Bulk User Management Scripts

批量用户管理脚本

Bulk User Creation from CSV

从CSV批量创建用户

bash
#!/bin/bash
bash
#!/bin/bash

bulk-create-users.sh

bulk-create-users.sh

CSV format: username,fullname,groups,shell

CSV format: username,fullname,groups,shell

Example: jsmith,Jane Smith,developers;docker,/bin/bash

Example: jsmith,Jane Smith,developers;docker,/bin/bash

CSV_FILE="${1:?Usage: $0 <users.csv>}"
while IFS=',' read -r username fullname groups shell; do

Skip header line

[[ "$username" == "username" ]] && continue
if id "$username" &>/dev/null; then echo "SKIP: User $username already exists" continue fi

Replace semicolons with commas for -G flag

group_list="${groups//;/,}"
useradd -m -s "$shell" -c "$fullname" -G "$group_list" "$username"

Generate a random temporary password

temp_pass=$(openssl rand -base64 12) echo "$username:$temp_pass" | chpasswd chage -d 0 "$username" # Force password change at first login
echo "CREATED: $username (groups: $group_list) temp-pass: $temp_pass" done < "$CSV_FILE"
undefined
CSV_FILE="${1:?Usage: $0 <users.csv>}"
while IFS=',' read -r username fullname groups shell; do

Skip header line

[[ "$username" == "username" ]] && continue
if id "$username" &>/dev/null; then echo "SKIP: User $username already exists" continue fi

Replace semicolons with commas for -G flag

group_list="${groups//;/,}"
useradd -m -s "$shell" -c "$fullname" -G "$group_list" "$username"

Generate a random temporary password

temp_pass=$(openssl rand -base64 12) echo "$username:$temp_pass" | chpasswd chage -d 0 "$username" # Force password change at first login
echo "CREATED: $username (groups: $group_list) temp-pass: $temp_pass" done < "$CSV_FILE"
undefined

Quick Access Audit Commands

快速访问审计命令

bash
undefined
bash
undefined

List non-system users (UID >= 1000)

List non-system users (UID >= 1000)

awk -F: '$3 >= 1000 && $3 < 65534 { printf "%-20s UID=%-6s Shell=%s\n", $1, $3, $7 }' /etc/passwd
awk -F: '$3 >= 1000 && $3 < 65534 { printf "%-20s UID=%-6s Shell=%s\n", $1, $3, $7 }' /etc/passwd

List users with sudo access

List users with sudo access

getent group sudo wheel 2>/dev/null
getent group sudo wheel 2>/dev/null

Find accounts that have never logged in

Find accounts that have never logged in

lastlog | awk '$0 ~ /Never logged in/ { print $1 }'
lastlog | awk '$0 ~ /Never logged in/ { print $1 }'

Find accounts with empty passwords

Find accounts with empty passwords

awk -F: '($2 == "" || $2 == "!") { print $1 }' /etc/shadow 2>/dev/null
undefined
awk -F: '($2 == "" || $2 == "!") { print $1 }' /etc/shadow 2>/dev/null
undefined

Troubleshooting

故障排查

SymptomDiagnostic CommandCommon Fix
User cannot log in
passwd -S username
,
faillock --user username
Unlock account, reset password, check shell
"not in sudoers" error
sudo -l -U username
Add user to sudo group or create sudoers.d file
Group membership not applied
id username
,
groups username
User must log out and back in for new groups
LDAP/AD user not found
id aduser
,
sssctl user-show aduser
Check SSSD status, clear cache:
sss_cache -E
Permission denied on file
ls -la file
,
getfacl file
Fix ownership/permissions, check SELinux context
PAM lockout after failed attempts
faillock --user username
faillock --user username --reset
Home directory not createdCheck
/etc/login.defs
CREATEHOME
Use
useradd -m
or enable
pam_mkhomedir
Password policy not enforcedCheck
/etc/pam.d/common-password
Install and configure
pam_pwquality
症状诊断命令常见修复方案
用户无法登录
passwd -S username
,
faillock --user username
解锁账户、重置密码、检查Shell设置
"not in sudoers"错误
sudo -l -U username
将用户添加到sudo组或创建sudoers.d文件
组成员身份未生效
id username
,
groups username
用户需重新登录以应用新组权限
LDAP/AD用户无法找到
id aduser
,
sssctl user-show aduser
检查SSSD状态,清除缓存:
sss_cache -E
文件访问权限被拒绝
ls -la file
,
getfacl file
修复所有权/权限,检查SELinux上下文
多次登录失败后被PAM锁定
faillock --user username
faillock --user username --reset
主目录未创建检查
/etc/login.defs
中的CREATEHOME配置
使用
useradd -m
或启用
pam_mkhomedir
密码策略未生效检查
/etc/pam.d/common-password
安装并配置
pam_pwquality

Related Skills

相关技能

  • linux-administration
    -- General Linux server management
  • ssh-configuration
    -- SSH key-based authentication for managed users
  • systemd-services
    -- Service accounts and systemd user instances
  • performance-tuning
    -- Resource limits per user via cgroups and ulimits
  • linux-administration
    —— 通用Linux服务器管理
  • ssh-configuration
    —— 为受管用户配置基于SSH密钥的认证
  • systemd-services
    —— 服务账户与systemd用户实例
  • performance-tuning
    —— 通过cgroups和ulimits设置每个用户的资源限制