Linux User and Group Management: From Creation to Permission Control1. Basics of the Linux User System2. Core User Management Commands3. User Group Management Commands4. Password Management5. User Information Query Commands6. Configuration File Details7. Password Policies and Security8. Practical Cases9. Best Security Practices10. Troubleshooting11. Summary
Linux User and Group Management: From Creation to Permission Control
In Linux, a true multi-user operating system, user and group management is the cornerstone of system security. From personal desktops to enterprise servers, a reasonable user management strategy can ensure system security, rational resource allocation, and efficient team collaboration. Today, we will delve into all aspects of Linux user management.
1. Basics of the Linux User System
1. User Types
-
Root User: The super administrator, UID 0, has the highest system privileges
-
System User: UID 1-999, used to run system services, usually not allowed to log in
-
Regular User: UID 1000+, used for daily operations and logins
2. User Group Types
-
Main Group: The group to which a user belongs by default when creating files
-
Additional Group: Extra groups to which a user belongs for specific permissions
3. Important Configuration Files
-
<span>/etc/passwd</span>: User account information -
<span>/etc/shadow</span>: User password information (encrypted) -
<span>/etc/group</span>: User group information -
<span>/etc/gshadow</span>: Group password information -
<span>/etc/login.defs</span>: Default settings for user creation -
<span>/etc/default/useradd</span>: Default values for the useradd command
2. Core User Management Commands
1. useradd – Create a New User
# Basic usage: create user
useradd username
# Common parameters explained
useradd -c"John Doe" john # Add user full name comment
useradd -d /home/john john # Specify home directory
useradd -s /bin/bash john # Specify login shell
useradd -u1500 john # Specify UID
useradd -g developers john # Specify main group
useradd -G wheel,admin john # Specify additional groups
useradd -m john # Create home directory
useradd -e2024-12-31 john # Set account expiration date
useradd -f30 john # Days until account is disabled after password expiration
# Create system user (for running services)
useradd -r-s /sbin/nologin apache_user
2. usermod – Modify User Attributes
# Change user login name
usermod -l new_username old_username
# Change user UID
usermod -u2000 username
# Change user home directory (and move contents)
usermod -d /new/home -m username
# Change user login shell
usermod -s /bin/zsh username
# Change user main group
usermod -g new_primary_group username
# Add user to additional groups (without overwriting existing groups)
usermod -aG group1,group2 username
# Change user comment information
usermod -c"New Comment" username
# Lock user account
usermod -L username
# Unlock user account
usermod -U username
3. userdel – Delete User
# Delete user (keep home directory)
userdel username
# Delete user and home directory
userdel -r username
# Force delete (even if user is logged in)
userdel -f username
Practical Case: Complete User Lifecycle Management
# Create development team user
useradd -c"Developer Alice" -d /home/alice -s /bin/bash -g developers -G docker,git -m alice
# Set password
passwd alice
# After a while, Alice moves to the testing team
usermod -g testers -G developers,docker alice
# Finally, Alice leaves the company
userdel -r alice
3. User Group Management Commands
1. groupadd – Create User Group
# Create regular group
groupadd developers
# Create system group
groupadd -r system_group
# Create group and specify GID
groupadd -g2000 developers
2. groupmod – Modify Group Attributes
# Change group name
groupmod -n new_groupname old_groupname
# Change GID
groupmod -g3000 groupname
3. groupdel – Delete User Group
# Delete empty group
groupdel groupname
# Note: If the group is a user's main group, it cannot be deleted directly
4. gpasswd – Group Management Tool
bash
# Set group password
gpasswd developers
# Add user to group
gpasswd -a username groupname
# Remove user from group
gpasswd -d username groupname
# Set group administrator
gpasswd -A username groupname
# Remove group password
gpasswd -r groupname
4. Password Management
1. passwd – Password Management
# Current user changes their own password
passwd
# Root user changes another user's password
passwd username
# Lock user account
passwd -l username
# Unlock user account
passwd -u username
# View password status
passwd -S username
# Delete user password (allow login without password)
passwd -d username
# Set password to expire immediately (force user to change on next login)
passwd -e username
2. chage – Password Policy Management
# View password expiration information
chage -l username
# Interactive set password policy
chage username
# Set last password change date
chage -d2024-06-15 username
# Set minimum days (cannot change password)
chage -m7 username
# Set maximum days (must change password)
chage -M90 username
# Set warning days before password expiration
chage -W7 username
# Set grace days after password expiration
chage -I14 username
# Set absolute expiration date
chage -E2024-12-31 username
5. User Information Query Commands
1. id – Display User Identity
# Display current user information
id
# Display specified user information
id username
# Display UID
id -u username
# Display GID
id -g username
# Display all groups
id -G username
# Display name instead of numeric ID
id -n username
2. who, w – View Logged-in Users
# View currently logged-in users
who
w
# View user login history
last
lastlog
# View specific user login information
last username
3. finger – User Information Query
# Install finger (if not installed)
yum install finger # RHEL/CentOS
apt install finger # Ubuntu/Debian
# Query user information
finger username
finger -s # Short format
finger -l # Long format
6. Configuration File Details
1. /etc/passwd File Format
username:password:UID:GID:comment:home_directory:shell
Field Descriptions:
-
<span>username</span>: Username -
<span>password</span>: x indicates password is in /etc/shadow -
<span>UID</span>: User ID -
<span>GID</span>: Main Group ID -
<span>comment</span>: User full name or description -
<span>home_directory</span>: Home directory path -
<span>shell</span>: Login shell
Example:
root:x:0:0:root:/root:/bin/bash
alice:x:1001:1001:Alice Developer:/home/alice:/bin/bash
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
2. /etc/shadow File Format
username:password:lastchg:min:max:warn:inactive:expire:flag
Field Descriptions:
-
<span>username</span>: Username -
<span>password</span>: Encrypted password (!! indicates locked) -
<span>lastchg</span>: Last password change date (days since 1970-1-1) -
<span>min</span>: Minimum password usage days -
<span>max</span>: Maximum password usage days -
<span>warn</span>: Warning days before password expiration -
<span>inactive</span>: Grace days after password expiration -
<span>expire</span>: Absolute expiration date of the account -
<span>flag</span>: Reserved field
3. /etc/group File Format
group_name:password:GID:user_list
Field Descriptions:
-
<span>group_name</span>: Group name -
<span>password</span>: Group password (rarely used) -
<span>GID</span>: Group ID -
<span>user_list</span>: List of group members (comma-separated)
7. Password Policies and Security
1. /etc/login.defs Configuration
# Password expiration policy
PASS_MAX_DAYS 90 # Maximum password validity period
PASS_MIN_DAYS 7 # Minimum password usage days
PASS_MIN_LEN 8 # Minimum password length
PASS_WARN_AGE 14 # Warning days before password expiration
# UID/GID range
UID_MIN 1000
UID_MAX 60000
GID_MIN 1000
GID_MAX 60000
# Home directory settings
CREATE_HOME yes
USERGROUPS_ENAB yes
2. PAM Password Complexity Configuration
Edit <span>/etc/pam.d/system-auth</span> or <span>/etc/pam.d/common-password</span>:
Using pam_pwquality:
password requisite pam_pwquality.so try_first_pass retry=3 \
minlen=8 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
Parameter Descriptions:
-
<span>minlen=8</span>: Minimum password length of 8 characters -
<span>dcredit=-1</span>: At least 1 digit -
<span>ucredit=-1</span>: At least 1 uppercase letter -
<span>lcredit=-1</span>: At least 1 lowercase letter -
<span>ocredit=-1</span>: At least 1 special character -
<span>retry=3</span>: Number of retries
3. Using pam_passwdqc (more powerful):
password requisite pam_passwdqc.so min=disabled,24,12,8,7
8. Practical Cases
Case 1: Create a Complete Development Team Environment
#!/bin/bash
# Create development team environment script
# Create user groups
groupadd developers
groupadd designers
groupadd managers
# Create shared directories
mkdir -p /team/{projects,tools,docs}
chmod 2775 /team/{projects,tools,docs} # SGID ensures file inherits group permissions
# Create development users
useradd -c"Lead Developer" -g developers -G wheel -m -s /bin/bash alice
useradd -c"Senior Developer" -g developers -m -s /bin/bash bob
useradd -c"UI Designer" -g designers -m -s /bin/bash carol
# Set directory permissions
chown :developers /team/projects
chown :developers /team/tools
chown :designers /team/docs
# Set ACL to allow cross-group collaboration
setfacl -m g:designers:rx /team/projects
setfacl -m g:developers:rx /team/docs
echo "Development team environment created!"
Case 2: Batch User Creation
#!/bin/bash
# Batch user creation script
USER_FILE="users.txt"
# User file format: username:fullname:groups
cat > $USER_FILE << EOF
john:John Smith:developers,wheel
jane:Jane Doe:designers
bob:Bob Johnson:developers
EOF
while IFS=: read username fullname groups; do
echo "Creating user: $username"
useradd -c "$fullname" -m -s /bin/bash $username
# Set default password
echo "${username}:Welcome123" | chpasswd
# Force first login to change password
chage -d 0 $username
# Add to groups
if [ -n "$groups" ]; then
usermod -aG $groups $username
fi
echo "User $username created successfully"
done < $USER_FILE
echo "Batch user creation completed!"
Case 3: User Account Audit Script
#!/bin/bash
# User account audit script
echo "=== User Account Audit Report ==="
echo "Generated on: $(date)"
echo
echo "1. Users with empty passwords:"
awk -F: '($2 == "") {print $1}' /etc/shadow
echo
echo "2. Users with passwords that never expire:"
awk -F: '($5 == 99999) {print $1}' /etc/shadow
echo
echo "3. Inactive users (not logged in for 30 days):"
lastlog -b 30 | grep -v "Never"
echo
echo "4. Users with UID 0 (excluding root):"
awk -F: '($3 == 0 && $1 != "root") {print $1}' /etc/passwd
echo
echo "5. Users without login shells:"
awk -F: '($7 == "/bin/false" || $7 == "/usr/sbin/nologin") {print $1}' /etc/passwd
echo
echo "Audit completed!"
9. Best Security Practices
1. Account Security Policies
# Regularly check and lock unused accounts
# Set strong password policies
# Restrict su and sudo permissions
# Monitor for abnormal login behavior
2. Regular Maintenance Tasks
#!/bin/bash
# Monthly user maintenance script
# Check for users with expiring passwords
echo "Users with passwords about to expire:"
chage -l $(cut -d: -f1 /etc/passwd) | grep "Password expires" | grep -v "never"
# Check for users who have not logged in for a long time
echo "Users who have not logged in for a long time:"
lastlog -b 90 | grep -v "Never"
# Check for accounts with empty passwords
echo "Accounts with empty passwords:"
awk -F: '($2 == "") {print $1}' /etc/shadow
# Send report to administrator
# mail -s "User Maintenance Report" [email protected] < /tmp/user_report.txt
3. Emergency Response Measures
# Emergency handling when suspicious accounts are found
username="suspicious_user"
# Immediately lock the account
passwd -l $username
usermod -L $username
# Terminate all processes of the user
pkill -9 -u $username
# Backup user data
tar -czf /backup/${username}_$(date +%Y%m%d).tar.gz /home/${username}
# Investigate login history
last $username
10. Troubleshooting
1. Diagnosing User Login Issues
# Check account status
passwd -S username
chage -l username
# Check shell permissions
ls -l $(grep username /etc/passwd | cut -d: -f7)
# Check home directory permissions
ls -ld /home/username
# Check PAM authentication logs
tail -f /var/log/secure # RHEL/CentOS
tail -f /var/log/auth.log # Ubuntu/Debian
2. Diagnosing Permission Issues
# Complete diagnostic script
diagnose_user() {
local user=$1
echo "=== Diagnosing User: $user ==="
# Basic identity information
echo "1. Identity Information:"
id $user
# Group information
echo -e "\n2. Group Information:"
groups $user
# Account status
echo -e "\n3. Account Status:"
passwd -S $user
chage -l $user 2>/dev/null || echo "chage information unavailable"
# Home directory
echo -e "\n4. Home Directory:"
local home=$(getent passwd $user | cut -d: -f6)
if [ -d "$home" ]; then
ls -ld "$home"
else
echo "Home directory does not exist: $home"
fi
# Login history
echo -e "\n5. Recent Logins:"
last -n 5 $user
}
# Usage example
diagnose_user alice
11. Summary
Linux user and group management is a core skill that system administrators must master. Through this article, you should now be able to:
-
Proficiently use user and group management commands
-
Understand the structure and function of user-related configuration files
-
Implement reasonable password policies and security measures
-
Batch create and manage user accounts
-
Diagnose and resolve user-related issues
Remember, good user management is not only a technical issue but also a security and organizational management issue. In practice, combine the organization’s security policies and business needs to formulate appropriate user management standards.
From personal experience, the following suggestions are particularly important:
-
Follow the Principle of Least Privilege: Users should only be granted the minimum permissions necessary to complete their work
-
Regular Audits: Regularly check user account status and permission assignments
-
Automated Management: Use scripts to automate routine user management tasks
-
Documentation: Record user management policies and operational procedures
-
Backup: Make backups before making significant changes to user accounts
Next Article Preview: In the next article, we will delve into Linux process management, covering process viewing, status monitoring, performance analysis, and troubleshooting, helping you master the core techniques of system resource management!
👍 Like, your recognition is the motivation for my creation!
⭐️ Bookmark, your favor is the direction of my efforts!
✏️ Comment, your opinions are the wealth of my progress!
PS: Due to changes in the public account platform’s push rules, if you don’t want to miss the content, remember to click “Looking” after reading, and add a “Star Mark” so that new articles will appear in your subscription list as soon as they are pushed. Click “Looking” to support me!