User and Group Management: Creating and Managing System Accounts

User and Group Management: Creating and Managing System Accounts
min read

User and Group Management: Creating and Managing System Accounts

User and group management is the cornerstone of Linux security and system organization. Whether you're setting up a personal computer, managing a server, or administering a multi-user system, understanding how to properly create and manage user accounts is essential for maintaining a secure and well-organized environment.

Understanding Linux Users and Groups

What Are Users in Linux?

In Linux, a user is an account that can log into the system and perform various operations based on assigned permissions. Every file, directory, and process is owned by a user, and the system uses this ownership to determine access rights.

Types of Users

1. Root User (Superuser): Has complete control over the system 2. System Users: Used by system services and daemons (UIDs typically 1-999) 3. Regular Users: Normal user accounts for people (UIDs typically 1000+)

What Are Groups in Linux?

Groups are collections of users that share common permissions. They provide an efficient way to manage access rights for multiple users simultaneously.

Types of Groups

1. Primary Group: Each user has exactly one primary group 2. Secondary Groups: Users can belong to multiple secondary groups 3. System Groups: Used by system services and applications

User Information Storage

Linux stores user and group information in several key files:

`/etc/passwd` - User Account Information

plaintext
username:x:UID:GID:GECOS:home_directory:shell

Example:

plaintext
john:x:1001:1001:John Doe,Room 101,555-1234:/home/john:/bin/bash

`/etc/shadow` - Password Information

plaintext
username:encrypted_password:last_change:min_age:max_age:warn:inactive:expire

`/etc/group` - Group Information

plaintext
group_name:x:GID:member_list

Example:

plaintext
developers:x:1010:john,jane,mike

`/etc/gshadow` - Group Password Information

Contains encrypted group passwords and group administrators.

Essential User Management Commands

The `useradd` Command: Creating New Users

The useradd command creates new user accounts with various options for customization.

Basic Syntax

bash
sudo useradd [options] username

Common Options

bash
# Create a basic user account
sudo useradd john

# Create user with home directory
sudo useradd -m john

# Create user with specific shell
sudo useradd -m -s /bin/bash john

# Create user with specific UID
sudo useradd -m -u 1500 john

# Create user with specific primary group
sudo useradd -m -g developers john

# Create user with secondary groups
sudo useradd -m -G sudo,docker john

# Create user with custom home directory
sudo useradd -m -d /custom/home/john john

# Create system user (for services)
sudo useradd -r -s /bin/false serviceuser

Complete User Creation Example

bash
# Create a developer user with all common settings
sudo useradd -m -s /bin/bash -c "John Developer" -G sudo,docker,developers john

# Set password for the new user
sudo passwd john

# Verify user creation
id john
cat /etc/passwd | grep john

The `usermod` Command: Modifying Existing Users

The usermod command allows you to modify existing user accounts.

Common Modifications

bash
# Change user's primary group
sudo usermod -g newgroup john

# Add user to secondary groups (append)
sudo usermod -aG sudo,docker john

# Change user's home directory
sudo usermod -d /new/home/john -m john

# Change user's shell
sudo usermod -s /bin/zsh john

# Change user's login name
sudo usermod -l newname oldname

# Lock a user account
sudo usermod -L john

# Unlock a user account
sudo usermod -U john

# Set account expiration date
sudo usermod -e 2025-12-31 john

# Change user's comment field
sudo usermod -c "John Smith - Senior Developer" john

The `userdel` Command: Removing Users

bash
# Delete user (keep home directory)
sudo userdel john

# Delete user and home directory
sudo userdel -r john

# Force delete (even if user is logged in)
sudo userdel -f john

Essential Group Management Commands

The `groupadd` Command: Creating Groups

bash
# Create a basic group
sudo groupadd developers

# Create group with specific GID
sudo groupadd -g 2000 developers

# Create system group
sudo groupadd -r webserver

The `groupmod` Command: Modifying Groups

bash
# Change group name
sudo groupmod -n newname oldname

# Change group GID
sudo groupmod -g 2500 developers

The `groupdel` Command: Removing Groups

bash
# Delete a group
sudo groupdel developers

# Note: Cannot delete if it's a user's primary group

The `gpasswd` Command: Group Administration

bash
# Add user to group
sudo gpasswd -a john developers

# Remove user from group
sudo gpasswd -d john developers

# Set group administrators
sudo gpasswd -A john,jane developers

# Set group members
sudo gpasswd -M john,jane,mike developers

Sudo Configuration and Management

Understanding Sudo

sudo (superuser do) allows regular users to execute commands with elevated privileges without knowing the root password.

The `/etc/sudoers` File

Important: Never edit /etc/sudoers directly. Always use visudo.

bash
# Edit sudoers file safely
sudo visudo

Basic Sudoers Syntax

plaintext
user    host=(runas) command

Common Sudoers Configurations

bash
# Allow user to run all commands as root
john    ALL=(ALL:ALL) ALL

# Allow user to run specific commands
john    ALL=(ALL) /bin/systemctl, /usr/bin/apt

# Allow group to run all commands
%sudo   ALL=(ALL:ALL) ALL

# Allow user to run commands without password
john    ALL=(ALL) NOPASSWD: ALL

# Allow user to run specific commands without password
john    ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx

Managing Sudo Access

bash
# Add user to sudo group (Debian/Ubuntu)
sudo usermod -aG sudo john

# Add user to wheel group (RHEL/CentOS)
sudo usermod -aG wheel john

# Check sudo access
sudo -l

# Run command as different user
sudo -u jane command

# Run command as specific group
sudo -g developers command

Practical User and Group Management Scenarios

Scenario 1: Setting Up a Development Team

bash
#!/bin/bash
# Script to set up a development team

# Create developers group
sudo groupadd developers

# Create shared project directory
sudo mkdir -p /projects/team-alpha
sudo chgrp developers /projects/team-alpha
sudo chmod 2775 /projects/team-alpha

# Create team members
for user in alice bob charlie; do
    sudo useradd -m -s /bin/bash -G developers,sudo "$user"
    sudo passwd "$user"
    echo "Created user: $user"
done

# Set up SSH access directory for each user
for user in alice bob charlie; do
    sudo mkdir -p "/home/$user/.ssh"
    sudo chmod 700 "/home/$user/.ssh"
    sudo chown "$user:$user" "/home/$user/.ssh"
done

echo "Development team setup complete!"

Scenario 2: Creating Service Accounts

bash
# Create a web server service user
sudo useradd -r -s /bin/false -d /var/www -c "Web Server User" www-data

# Create a database service user
sudo useradd -r -s /bin/false -d /var/lib/mysql -c "MySQL Server" mysql

# Create a monitoring service user
sudo useradd -r -s /bin/false -d /opt/monitoring -c "Monitoring Service" monitor

Scenario 3: Implementing Role-Based Access

bash
# Create role-based groups
sudo groupadd admins
sudo groupadd operators
sudo groupadd readonly-users

# Add users to appropriate groups
sudo usermod -aG admins alice
sudo usermod -aG operators bob
sudo usermod -aG readonly-users charlie

# Configure sudoers for different roles
echo "%admins ALL=(ALL:ALL) ALL" | sudo tee -a /etc/sudoers.d/roles
echo "%operators ALL=(ALL) /bin/systemctl, /usr/bin/service" | sudo tee -a /etc/sudoers.d/roles
echo "%readonly-users ALL=(ALL) /bin/cat, /bin/ls, /usr/bin/tail" | sudo tee -a /etc/sudoers.d/roles

Advanced User Management

User Account Policies

Password Policies

bash
# Set password expiration
sudo chage -M 90 john          # Maximum 90 days
sudo chage -m 7 john           # Minimum 7 days between changes
sudo chage -W 7 john           # Warning 7 days before expiration

# View password policy for user
sudo chage -l john

# Force password change on next login
sudo chage -d 0 john

Account Locking and Unlocking

bash
# Lock user account
sudo passwd -l john
# or
sudo usermod -L john

# Unlock user account
sudo passwd -u john
# or
sudo usermod -U john

# Check account status
sudo passwd -S john

Bulk User Management

Creating Multiple Users from File

bash
# Create users.txt file
cat > users.txt << EOF
alice:Alice Smith:Development
bob:Bob Johnson:Operations
charlie:Charlie Brown:Support
EOF

# Script to create users from file
#!/bin/bash
while IFS=':' read -r username fullname department; do
    sudo useradd -m -s /bin/bash -c "$fullname - $department" "$username"
    sudo passwd "$username"
    echo "Created user: $username"
done < users.txt

Home Directory Management

bash
# Create user without home directory
sudo useradd --no-create-home john

# Create home directory later
sudo mkdir /home/john
sudo cp -r /etc/skel/. /home/john/
sudo chown -R john:john /home/john
sudo chmod 755 /home/john

# Change home directory location
sudo usermod -d /new/location/john -m john

Monitoring and Auditing Users

Viewing User Information

bash
# List all users
cat /etc/passwd | cut -d: -f1

# List all groups
cat /etc/group | cut -d: -f1

# Show user details
id username
finger username        # If finger is installed
getent passwd username

# Show user's groups
groups username

# Show who's logged in
who
w
last

# Show login history
last username
lastlog

User Activity Monitoring

bash
# Monitor user logins
sudo tail -f /var/log/auth.log    # Debian/Ubuntu
sudo tail -f /var/log/secure      # RHEL/CentOS

# Check failed login attempts
sudo lastb

# Monitor sudo usage
sudo tail -f /var/log/auth.log | grep sudo

Security Best Practices

User Account Security

1. Use Strong Password Policies

bash
# Install password quality checking
sudo apt install libpam-pwquality

# Configure in /etc/pam.d/common-password
password requisite pam_pwquality.so retry=3 minlen=8 maxrepeat=2

2. Regular Account Audits

bash
#!/bin/bash
# User audit script

echo "=== User Account Audit ==="
echo "Users with UID 0 (root privileges):"
awk -F: '$3 == 0 {print $1}' /etc/passwd

echo -e "\nUsers with empty passwords:"
sudo awk -F: '$2 == "" {print $1}' /etc/shadow

echo -e "\nUsers with home directories:"
awk -F: '$6 ~ /^\/home/ {print $1, $6}' /etc/passwd

echo -e "\nUsers in sudo group:"
getent group sudo | cut -d: -f4 | tr ',' '\n'

3. Disable Unused Accounts

bash
# Lock inactive accounts
sudo passwd -l unused-user

# Set account expiration
sudo usermod -e 1 unused-user

Group Security

1. Regular Group Membership Reviews

bash
# List all group memberships
for group in $(cut -d: -f1 /etc/group); do
    echo "Group: $group"
    getent group "$group" | cut -d: -f4 | tr ',' '\n' | sed 's/^/  /'
    echo
done

2. Principle of Least Privilege

bash
# Remove user from unnecessary groups
sudo gpasswd -d username groupname

# Review sudo access regularly
sudo visudo

Troubleshooting Common Issues

User Creation Problems

bash
# Check if username already exists
id username 2>/dev/null && echo "User exists" || echo "User does not exist"

# Check available UIDs
awk -F: '{print $3}' /etc/passwd | sort -n | tail -10

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

Group Management Issues

bash
# Check group membership
groups username

# Fix primary group assignment
sudo usermod -g correct-group username

# Remove user from all secondary groups
sudo usermod -G "" username

Sudo Access Problems

bash
# Check sudo access
sudo -l -U username

# Verify sudoers syntax
sudo visudo -c

# Check sudo group membership
getent group sudo | grep username

Hands-On Practice: Complete User Management Workshop

Exercise 1: Development Team Setup

bash
#!/bin/bash
# Create a complete development environment

# 1. Create groups
sudo groupadd frontend-devs
sudo groupadd backend-devs
sudo groupadd devops

# 2. Create users with different roles
sudo useradd -m -s /bin/bash -G frontend-devs,sudo alice
sudo useradd -m -s /bin/bash -G backend-devs,sudo bob
sudo useradd -m -s /bin/bash -G devops,sudo charlie

# 3. Set passwords
echo "alice:TempPass123!" | sudo chpasswd
echo "bob:TempPass123!" | sudo chpasswd
echo "charlie:TempPass123!" | sudo chpasswd

# 4. Force password change on first login
sudo chage -d 0 alice bob charlie

# 5. Create project directories
sudo mkdir -p /projects/{frontend,backend,infrastructure}
sudo chgrp frontend-devs /projects/frontend
sudo chgrp backend-devs /projects/backend
sudo chgrp devops /projects/infrastructure

# 6. Set appropriate permissions
sudo chmod 2775 /projects/*

echo "Development environment setup complete!"

Exercise 2: Service Account Creation

bash
#!/bin/bash
# Create service accounts for common applications

services=("nginx" "mysql" "redis" "nodejs" "python-app")

for service in "${services[@]}"; do
    echo "Creating service account for $service"
    sudo useradd -r -s /bin/false -d "/var/lib/$service" -c "$service service account" "$service"
    sudo mkdir -p "/var/lib/$service"
    sudo chown "$service:$service" "/var/lib/$service"
    sudo chmod 750 "/var/lib/$service"
done

echo "Service accounts created successfully!"

Key Takeaways

- useradd: Create new user accounts with various options

  • usermod: Modify existing user accounts and settings
  • groupadd/groupmod: Manage groups and group memberships
  • sudo configuration: Control elevated privileges safely
  • Security principles: Implement least privilege and regular audits
  • Account policies: Set password expiration and locking policies
  • Monitoring: Track user activity and login attempts

  • What's Next?

    With solid user and group management skills, you're ready to tackle more advanced system administration topics like file permissions, network configuration, and service management. Understanding users and groups is fundamental to securing your Linux system and organizing access control effectively.

    Quick Reference Commands

    bash
    # User Management
    sudo useradd -m -s /bin/bash username    # Create user with home
    sudo usermod -aG group username          # Add to group
    sudo userdel -r username                 # Delete user and home
    sudo passwd username                     # Set password
    id username                              # Show user info
    
    # Group Management
    sudo groupadd groupname                  # Create group
    sudo gpasswd -a username groupname       # Add user to group
    sudo gpasswd -d username groupname       # Remove from group
    groups username                          # Show user's groups
    
    # Sudo Management
    sudo visudo                              # Edit sudoers safely
    sudo -l                                  # List sudo privileges
    sudo usermod -aG sudo username           # Add sudo access
    
    # Account Policies
    sudo chage -l username                   # View password policy
    sudo passwd -l username                  # Lock account
    sudo passwd -u username                  # Unlock account

    Remember: User and group management is about security, organization, and access control. Always follow the principle of least privilege and regularly audit your user accounts and permissions.

    ---

    🚀 Continue Your Linux Journey

    This is Part 8 of our comprehensive Linux mastery series.

    Previous: Package Management - Master software installation and management

    Next: Process Management - Learn to monitor and control system processes

    📚 Complete Linux Series Navigation

    Intermediate Skills:

  • Part 7: Package Management
  • Part 8: User & Group ManagementYou are here
  • Part 9: Process Management
  • Part 10: Environment Variables
  • Part 11: Automation with Cron

    Building Security? Continue with process management to control system resources and applications!

  • - Linux Permissions & Security

  • SSH Mastery & Secure Remote Access

    ---

    Ready to secure your files and directories? Next, we'll explore Linux file permissions and ownership to complete your understanding of Linux security fundamentals.

  • Made With Love on