BLOG POSTS
How to Add and Delete Users on a CentOS 7 Server

How to Add and Delete Users on a CentOS 7 Server

User management is a critical aspect of CentOS 7 server administration that every developer and sysadmin needs to master. Whether you’re setting up a multi-user development environment, managing team access to production servers, or implementing proper security protocols, knowing how to efficiently add and remove users can save you hours of troubleshooting down the road. This guide walks you through the complete process of user management on CentOS 7, covering everything from basic user creation to advanced permission handling and common gotchas that can trip up even experienced administrators.

Understanding User Management in CentOS 7

CentOS 7 handles user accounts through a combination of system files and utilities that manage user information, authentication, and permissions. The primary files involved are /etc/passwd for user account information, /etc/shadow for password data, and /etc/group for group memberships.

When you create a user, CentOS automatically assigns a User ID (UID) and Group ID (GID), creates a home directory, and sets up basic shell access. The system uses UIDs below 1000 for system accounts and starts regular user accounts from UID 1000 onwards.

Command Primary Function Key Features Best Use Case
useradd Add new users Flexible options, batch creation Automated user provisioning
adduser Interactive user creation Guided prompts, automatic setup Manual user setup with prompts
userdel Remove users Clean removal, home directory handling User deprovisioning
usermod Modify existing users Change attributes, group membership User account maintenance

Adding Users: Step-by-Step Implementation

The most straightforward way to add a user is using the useradd command. Here’s the basic syntax and common variations:

# Basic user creation
sudo useradd username

# Create user with home directory and bash shell
sudo useradd -m -s /bin/bash username

# Create user with specific UID and primary group
sudo useradd -u 1500 -g developers -m -s /bin/bash john

# Create system user (UID below 1000)
sudo useradd -r -s /bin/false serviceaccount

After creating the user, you’ll need to set a password:

# Set password interactively
sudo passwd username

# Set password non-interactively (useful for scripts)
echo "newpassword" | sudo passwd --stdin username

For more control over user creation, you can specify additional parameters:

# Comprehensive user creation with all options
sudo useradd \
  -m \
  -d /home/customhome \
  -s /bin/bash \
  -g primarygroup \
  -G wheel,developers \
  -u 1501 \
  -c "Full Name" \
  -e 2024-12-31 \
  username

Here’s what each option does:

  • -m: Create home directory
  • -d: Specify custom home directory path
  • -s: Set login shell
  • -g: Primary group
  • -G: Secondary groups (comma-separated)
  • -u: Specific UID
  • -c: Comment field (usually full name)
  • -e: Account expiration date

Real-World User Creation Examples

Let’s look at some practical scenarios you’ll encounter in production environments:

Developer Environment Setup

# Create a development team with shared group access
sudo groupadd developers
sudo useradd -m -g developers -G wheel -s /bin/bash alice
sudo useradd -m -g developers -G wheel -s /bin/bash bob
sudo passwd alice
sudo passwd bob

# Set up shared development directory
sudo mkdir /opt/projects
sudo chown :developers /opt/projects
sudo chmod 2775 /opt/projects

Service Account Creation

# Create service account for web application
sudo useradd -r -s /bin/false -d /opt/webapp webapp
sudo mkdir -p /opt/webapp
sudo chown webapp:webapp /opt/webapp

Temporary Contractor Access

# Create user with 30-day expiration
sudo useradd -m -s /bin/bash -e $(date -d "+30 days" +%Y-%m-%d) contractor1
sudo passwd contractor1

# Add to specific project group
sudo usermod -a -G project_alpha contractor1

Deleting Users: Complete Removal Process

User deletion requires careful consideration of data preservation and system cleanup. The userdel command provides several options:

# Basic user deletion (keeps home directory)
sudo userdel username

# Delete user and home directory
sudo userdel -r username

# Force deletion even if user is logged in
sudo userdel -f username

# Remove user and all files owned by user
sudo userdel -r -f username

For production systems, you’ll often want a more controlled approach:

# Step-by-step safe user removal

# 1. Check if user is currently logged in
who | grep username
ps -u username

# 2. Kill user processes if necessary
sudo pkill -u username

# 3. Backup user data before deletion
sudo tar -czf /backups/username_backup_$(date +%Y%m%d).tar.gz /home/username

# 4. Remove user but keep home directory initially
sudo userdel username

# 5. Archive and remove home directory after verification
sudo mv /home/username /home/deleted_username_$(date +%Y%m%d)

Advanced User Management Techniques

Here are some advanced scenarios and techniques that experienced administrators use:

Batch User Operations

# Create multiple users from a list
#!/bin/bash
users=("dev1" "dev2" "dev3" "tester1" "tester2")
for user in "${users[@]}"; do
    sudo useradd -m -g developers -s /bin/bash "$user"
    echo "temppass123" | sudo passwd --stdin "$user"
    sudo chage -d 0 "$user"  # Force password change on first login
done

User Account Monitoring Script

#!/bin/bash
# Monitor user accounts and their status

echo "=== User Account Status ==="
echo "Active users with home directories:"
getent passwd | awk -F: '$3 >= 1000 && $7 !~ /nologin|false/ {print $1, $3, $6}'

echo -e "\n=== Users with sudo access ==="
grep -E '^(wheel|sudo):' /etc/group | cut -d: -f4 | tr ',' '\n'

echo -e "\n=== Recently created users (last 7 days) ==="
find /home -maxdepth 1 -type d -newerct "7 days ago" -ls

Setting Up SSH Key Authentication

# Set up SSH keys for new user
sudo -u username mkdir /home/username/.ssh
sudo -u username chmod 700 /home/username/.ssh
sudo -u username touch /home/username/.ssh/authorized_keys
sudo -u username chmod 600 /home/username/.ssh/authorized_keys

# Add public key (replace with actual key)
echo "ssh-rsa AAAAB3NzaC1yc2E..." | sudo -u username tee -a /home/username/.ssh/authorized_keys

Common Issues and Troubleshooting

Even experienced administrators run into these common issues:

User Creation Failures

# Check if username already exists
getent passwd username

# Verify available UIDs
awk -F: '$3 >= 1000 && $3 < 2000 {print $3}' /etc/passwd | sort -n

# Check group existence before assignment
getent group groupname

Permission Problems After User Creation

# Fix home directory permissions
sudo chown -R username:username /home/username
sudo chmod 755 /home/username

# Verify user shell is valid
grep username /etc/passwd
chsh -s /bin/bash username

Deletion Issues

# Find all files owned by user before deletion
sudo find / -user username -type f 2>/dev/null

# Check for active processes
sudo lsof -u username

# Remove user from all groups
sudo gpasswd -d username groupname

Security Best Practices and Performance Considerations

Implementing proper user management goes beyond basic creation and deletion. Here are essential security practices:

  • Use strong password policies: Configure PAM modules in /etc/pam.d/system-auth to enforce complexity requirements
  • Implement account lockout: Set up faillock to prevent brute force attacks
  • Regular auditing: Use lastlog and last commands to monitor user activity
  • Proper group management: Minimize users in the wheel group and use specific groups for different access levels
  • Home directory encryption: Consider using encrypted home directories for sensitive environments
# Set up password aging policy
sudo chage -M 90 -m 7 -W 7 username

# Configure account lockout after failed attempts
sudo authconfig --enablefaillock --faillockargs="deny=3 unlock_time=600" --update

Integration with Configuration Management

For larger environments, consider integrating user management with tools like Ansible, Puppet, or Salt. Here's a basic Ansible playbook example:

---
- name: Manage users on CentOS 7
  hosts: centos_servers
  become: yes
  vars:
    developers:
      - { name: "alice", groups: "wheel,developers" }
      - { name: "bob", groups: "developers" }
  
  tasks:
    - name: Create developer group
      group:
        name: developers
        state: present
    
    - name: Create developer users
      user:
        name: "{{ item.name }}"
        groups: "{{ item.groups }}"
        shell: /bin/bash
        createhome: yes
        state: present
      loop: "{{ developers }}"

User management in CentOS 7 becomes significantly easier once you understand the underlying mechanisms and common patterns. The key is to develop consistent procedures for your environment and automate repetitive tasks where possible. For additional information and advanced configuration options, check the official Red Hat Enterprise Linux 7 System Administrator's Guide and the comprehensive CentOS documentation.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked