Skip to main content

Linux User & Group Management

 User and Group Management: Complete Linux Administration Guide

Learn how to manage users, groups, and permissions like a professional system administrator.

📅 Published: Feb 2026
⏱️ Estimated Reading Time: 15 minutes
🏷️ Tags: Linux Users, Group Management, sudo, Security, System Administration


👥 Creating and Managing Users & Groups

Why User Management Matters in Linux

In Linux, every action is performed by a user. Even the system itself runs as users (like root for administration or www-data for web services). Think of it like an office building:

  • Root user = Building manager (has master keys to everything)

  • Regular users = Office workers (access only their own offices)

  • System users = Maintenance staff (specific access for specific tasks)

This separation is crucial for security. If one user's account gets compromised, the damage is limited. If everyone had root access, one mistake could take down the entire system.

Understanding User Types

  1. Root User (Superuser)

    • User ID: 0

    • Can do anything on the system

    • Like having administrator password on Windows

    • Should rarely be used directly

  2. Regular Users

    • User IDs: 1000+

    • Limited permissions

    • Can only access their own files and shared resources

    • Most daily work happens here

  3. System Users

    • User IDs: 1-999

    • Created for specific services (nginx, mysql, etc.)

    • Limited to only what they need to function

Creating Your First User

bash
# Basic user creation
sudo adduser john

# What happens when you run this?
# 1. Creates entry in /etc/passwd
# 2. Creates home directory (/home/john)
# 3. Sets up default shell (usually /bin/bash)
# 4. Creates personal group (john)
# 5. Copies default configuration files

Interactive creation (recommended for beginners):

bash
sudo adduser john
# System will ask for:
# Password (twice, for verification)
# Full name (optional)
# Room number, phone, etc. (optional)
# Confirm information is correct

Non-interactive creation (for automation):

bash
sudo useradd -m -s /bin/bash -c "John Doe" johndoe
# -m: Create home directory
# -s: Set default shell
# -c: Comment/description

Managing Existing Users

bash
# Modify user information
sudo usermod -aG developers john  # Add john to developers group
sudo usermod -s /bin/zsh john     # Change john's shell to zsh
sudo usermod -L john              # Lock john's account
sudo usermod -U john              # Unlock john's account

# Delete users
sudo userdel john                 # Delete user only
sudo userdel -r john              # Delete user + home directory

Working with Groups

Why groups are important: Groups allow you to manage permissions for multiple users at once. For example, all developers need access to the code directory, all DBAs need database access.

bash
# Create a new group
sudo groupadd developers

# Add user to group
sudo usermod -aG developers john
# The -aG means "append to group" - important! Without -a, user is removed from other groups

# Check user's groups
groups john
id john

# Create user with specific groups
sudo useradd -m -G developers,designers sarah

# Remove user from group
sudo gpasswd -d john developers

Real-World Example: Project Team Setup

Imagine you're setting up a development environment for a project team:

bash
# Create project groups
sudo groupadd web-developers
sudo groupadd database-admins
sudo groupadd project-managers

# Create users with appropriate groups
sudo useradd -m -G web-developers,project-managers alice
sudo useradd -m -G web-developers bob
sudo useradd -m -G database-admins charlie

# Create shared project directory
sudo mkdir -p /projects/website
sudo chown :web-developers /projects/website
sudo chmod 2775 /projects/website  # Sets group sticky bit

# Now all web-developers can collaborate in /projects/website

🔐 sudo and Privilege Escalation

What is sudo?

sudo (Super User DO) allows permitted users to run commands as root or another user. It's like having a temporary "admin pass" that expires after each command.

Why use sudo instead of logging in as root?

  1. Audit trail: Every sudo command is logged (who ran what and when)

  2. Security: No need to share root password

  3. Granular control: You can give specific privileges (e.g., only restart services)

Basic sudo Usage

bash
# Run a single command as root
sudo apt update

# Edit a protected file
sudo nano /etc/hosts

# Run command as another user
sudo -u www-data whoami  # Runs whoami as www-data user

# Open a root shell (use sparingly!)
sudo -i
sudo su -

Understanding the sudoers File

The magic happens in /etc/sudoers. This file controls who can run what as whom.

⚠️ IMPORTANT: Never edit /etc/sudoers directly with a normal text editor! Always use:

bash
sudo visudo

This command:

  1. Locks the file to prevent multiple edits

  2. Checks syntax before saving

  3. Prevents you from locking yourself out

Common sudoers Configurations

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

# Allow developers group to run apt commands without password
%developers ALL=(ALL) NOPASSWD: /usr/bin/apt

# Allow specific commands with specific arguments
alice   ALL=(ALL) /usr/bin/systemctl restart nginx, \
                  /usr/bin/systemctl status nginx

# Allow bob to run commands as www-data user
bob     ALL=(www-data) /usr/bin/systemctl, /usr/bin/journalctl

Breaking down the syntax:

text
user    hosts=(run-as) commands
john    ALL=(ALL:ALL) ALL
↑        ↑    ↑        ↑
Who      Where As whom What

Practical sudo Examples for DevOps

bash
# Allow deployment user to restart services
# In /etc/sudoers:
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart *, \
                           /usr/bin/systemctl status *

# Allow monitoring user to check system stats
monitor ALL=(ALL) NOPASSWD: /usr/bin/top, /usr/bin/df, /usr/bin/free

# Allow developers to manage Docker containers
%docker-users ALL=(ALL) /usr/bin/docker, /usr/bin/docker-compose

Best Practices for sudo

  1. Use groups, not individual users when possible

  2. Be specific with allowed commands

  3. Use NOPASSWD sparingly (only for automated scripts)

  4. Regularly review sudo logssudo grep sudo /var/log/auth.log

  5. Implement time restrictions if needed


🔑 Password Management & Security

Understanding Linux Password Storage

Linux doesn't store actual passwords. Instead, it stores hashes (encrypted versions) in /etc/shadow.

How it works:

  1. You type password: mypassword123

  2. System encrypts it: $6$salt$hashedversion

  3. Stores only the hash

  4. When you login, system hashes what you type and compares

bash
# View password aging info
sudo chage -l john

# Set password expiration
sudo chage -M 90 john      # Must change every 90 days
sudo chage -W 7 john       # Warn 7 days before expiration
sudo chage -I 30 john      # Inactive account lock after 30 days
sudo chage -E 2024-12-31 john  # Account expires on date

Password Policies

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

# Configure in /etc/security/pwquality.conf
minlen = 12      # Minimum password length
minclass = 3     # Require 3 character types (upper, lower, number, special)
maxrepeat = 2    # Maximum consecutive repeated characters

Managing User Passwords

bash
# Change your own password
passwd

# Change another user's password (as root)
sudo passwd john

# Lock an account (prevent login)
sudo passwd -l john
# This adds '!' in front of password hash in /etc/shadow

# Unlock an account
sudo passwd -u john

# Force password change on next login
sudo passwd -e john

SSH Key Authentication (Better than Passwords)

For servers, SSH keys are more secure than passwords:

bash
# Generate SSH key pair
ssh-keygen -t rsa -b 4096 -C "john@company.com"

# Copy public key to server
ssh-copy-id john@server-ip

# Disable password authentication (after testing keys work)
# In /etc/ssh/sshd_config:
PasswordAuthentication no
PubkeyAuthentication yes

📋 Understanding /etc/passwd and /etc/group

The /etc/passwd File

This file contains user account information. Each line represents one user with seven fields separated by colons:

text
john:x:1001:1001:John Doe:/home/john:/bin/bash
└─┬─┘ ┬ ┬──┘ ┬──┘ └──┬──┘ └──┬──┘ └──┬────┘
  │   │ │    │       │        │       └── Shell
  │   │ │    │       │        └── Home Directory
  │   │ │    │       └── User Information (GECOS)
  │   │ │    └── Group ID (GID)
  │   │ └── User ID (UID)
  │   └── Password (x means password in /etc/shadow)
  └── Username

Fields explained:

  1. Username: Login name (john)

  2. Password: 'x' means password stored in /etc/shadow

  3. UID: User ID (0=root, 1-999=system, 1000+=regular)

  4. GID: Primary Group ID

  5. GECOS: Optional user info (full name, phone, etc.)

  6. Home Directory: User's personal folder

  7. Shell: Default shell program

bash
# View /etc/passwd
cat /etc/passwd

# Search for specific user
grep john /etc/passwd

# Count total users
wc -l /etc/passwd  # Includes system users

The /etc/group File

This file contains group information. Each line has four fields:

text
developers:x:1002:alice,bob,charlie
└──┬─────┘ ┬ ┬──┘ └─────┬────────┘
   │       │ │          └── Members (comma separated)
   │       │ └── Group ID (GID)
   │       └── Password (rarely used)
   └── Group Name

Important notes about groups:

  • Each user has a primary group (in /etc/passwd)

  • Users can belong to multiple secondary groups (in /etc/group)

  • The primary group is used for new file creation

bash
# View groups
cat /etc/group

# Find which groups a user belongs to
groups john
id john

# Find all users in a group
getent group developers

The /etc/shadow File

This sensitive file contains encrypted passwords and password aging information:

text
john:$6$salt$hashedpassword:18647:0:99999:7:::
└─┬─┘ └─────┬─────┘ └─┬─┘ ┬ ┬──┬──┘ ┬
  │         │         │   │ │  │    └── Inactive days
  │         │         │   │ │  └── Warning period
  │         │         │   │ └── Max password age
  │         │         │   └── Min password age
  │         │         └── Last password change
  │         └── Encrypted password
  └── Username

Shadow file permissions:

bash
ls -l /etc/shadow
# -rw-r----- 1 root shadow
# Only root can read/write, shadow group can read

 Hands-On Practice Scenarios

Scenario 1: Setting Up a Development Team

Task: Create accounts for 3 developers who need to collaborate on /var/www/project/

bash
# 1. Create group
sudo groupadd webdev

# 2. Create users
sudo useradd -m -G webdev -s /bin/bash alice
sudo useradd -m -G webdev -s /bin/bash bob
sudo useradd -m -G webdev -s /bin/bash charlie

# 3. Set passwords
echo "alice:SecurePass123" | sudo chpasswd
echo "bob:SecurePass456" | sudo chpasswd
echo "charlie:SecurePass789" | sudo chpasswd

# 4. Create project directory with group permissions
sudo mkdir -p /var/www/project
sudo chown root:webdev /var/www/project
sudo chmod 2775 /var/www/project  # Group sticky bit

# 5. Verify setup
ls -ld /var/www/project
getent group webdev

Scenario 2: Implementing sudo Policies

Task: Create sudo access for different team roles

bash
# 1. Create groups for different access levels
sudo groupadd junior-admins
sudo groupadd senior-admins

# 2. Create users
sudo useradd -m -G junior-admins james
sudo useradd -m -G senior-admins sarah

# 3. Configure sudoers (using visudo)
sudo visudo

# Add these lines:
%junior-admins ALL=(ALL) /usr/bin/systemctl status *, \
                         /usr/bin/systemctl restart nginx, \
                         /usr/bin/apt update

%senior-admins ALL=(ALL) ALL

# 4. Test access
sudo -u james systemctl status nginx  # Should work
sudo -u james useradd testuser        # Should fail
sudo -u sarah useradd testuser        # Should work

Scenario 3: User Account Audit

Task: Check system for inactive accounts and weak passwords

bash
#!/bin/bash
# Save as audit_users.sh

echo "=== User Account Audit ==="
echo "Run on: $(date)"
echo

# 1. List all users
echo "1. All system users:"
cut -d: -f1 /etc/passwd
echo

# 2. Check for users without passwords
echo "2. Users without passwords:"
sudo awk -F: '($2 == "" || $2 == "!") {print $1}' /etc/shadow
echo

# 3. Check password expiration
echo "3. Password expiration info:"
for user in $(cut -d: -f1 /etc/passwd); do
    expires=$(sudo chage -l $user 2>/dev/null | grep "Account expires" | cut -d: -f2)
    if [ "$expires" != " never" ]; then
        echo "$user expires on: $expires"
    fi
done
echo

# 4. Check last login
echo "4. Last login times:"
lastlog | grep -v "Never logged in"

🚨 Security Best Practices

1. Regular User Audits

bash
# Check for users with UID 0 (should only be root)
awk -F: '($3 == 0) {print $1}' /etc/passwd

# Check for users without passwords
sudo awk -F: '($2 == "") {print $1}' /etc/shadow

# Check for inactive accounts
lastlog -b 90  # Users not logged in for 90 days

2. Implement Password Policies

bash
# Set global password policy
sudo nano /etc/login.defs
# Change:
PASS_MAX_DAYS   90
PASS_MIN_DAYS   1
PASS_WARN_AGE   7

3. Monitor sudo Usage

bash
# Check sudo logs
sudo grep sudo /var/log/auth.log

# Setup email alerts for root access
# In /etc/sudoers:
Defaults    mailto="admin@company.com"
Defaults    mail_always

4. Disable Unused Accounts

bash
# Instead of deleting, disable accounts
sudo usermod -L username      # Lock account
sudo usermod -s /sbin/nologin username  # Disable shell access

📊 Quick Reference Cheat Sheet

TaskCommandDescription
Create usersudo adduser usernameInteractive user creation
Create usersudo useradd -m usernameNon-interactive creation
Delete usersudo userdel -r usernameRemove user + home
Modify usersudo usermod -aG group userAdd to group
Change shellsudo usermod -s /bin/zsh userChange default shell
Create groupsudo groupadd groupnameCreate new group
Delete groupsudo groupdel groupnameRemove group
Change passwordpasswdChange your password
Change other's passwordsudo passwd usernameAdmin change password
Lock accountsudo passwd -l usernamePrevent login
Check user infoid usernameShow UID, GID, groups
Check groupsgroups usernameShow user's groups
View sudoerssudo visudoEdit sudo configuration
Check user activitylast usernameShow login history
Check passwd filegetent passwd usernameView user entry

🎓 Learning Path Recommendation

Week 1-2: Practice basic user/group creation and deletion
Week 3-4: Understand /etc/passwd, /etc/group, /etc/shadow structure
Week 5-6: Master sudo configuration and security policies
Week 7-8: Implement real-world scenarios and audits


🔗 Practice with Real Environments

The best way to learn user management is through hands-on practice in safe environments where you can make mistakes without consequences.

👉 Practice user and group management with real scenarios at:
https://devops.trainwithsky.com/

Our interactive labs provide:

  • Step-by-step guided exercises

  • Real-world simulation environments

  • Instant feedback on your commands

  • Progress tracking and certification


Common Questions Answered

Q: What's the difference between adduser and useradd?
A: adduser is user-friendly with prompts and default setups. useradd is lower-level and needs all options specified. Start with adduser.

Q: How do I give a user admin rights?
A: Add them to the sudo group: sudo usermod -aG sudo username

Q: What happens when I delete a user but not their home directory?
A: The files remain but ownership changes to the UID number. These become "orphaned files."

Q: How can I see who's currently logged in?
A: Use who or w command to see active users.

Q: What's the safest way to give limited root access?
A: Use sudo with specific commands in /etc/sudoers rather than giving full sudo access.

Need help with specific user management scenarios? Ask below and our community will help! 👇

Comments

Popular posts from this blog

Introduction to Terraform – The Future of Infrastructure as Code

  Introduction to Terraform – The Future of Infrastructure as Code In today’s fast-paced DevOps world, managing infrastructure manually is outdated . This is where Terraform comes in—a powerful Infrastructure as Code (IaC) tool that allows you to define, provision, and manage cloud infrastructure efficiently . Whether you're working with AWS, Azure, Google Cloud, or on-premises servers , Terraform provides a declarative, automation-first approach to infrastructure deployment. Shape Your Future with AI & Infinite Knowledge...!! Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! In today’s digital-first world, agility and automation are no longer optional—they’re essential. Companies across the globe are rapidly shifting their operations to the cloud to keep up with the pace of innovatio...

📊 Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd

  Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd Monitoring and logging are essential for maintaining a healthy and well-performing Kubernetes cluster. In this guide, we’ll cover why monitoring is important, key monitoring tools like Prometheus and Grafana, and logging tools like Fluentd to help you gain visibility into your cluster’s performance and logs. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction In today’s fast-paced cloud-native environment, Kubernetes has emerged as the de-facto container orchestration platform. But deploying and managing applications in Kubernetes is just half the ba...

🔒 Kubernetes Security – RBAC, Network Policies, and Secrets Management

  Kubernetes Security – RBAC, Network Policies, and Secrets Management Security is a critical aspect of managing Kubernetes clusters. In this guide, we'll cover essential security mechanisms like Role-Based Access Control (RBAC) , Network Policies , and Secrets Management to help you secure your Kubernetes environment effectively. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction: Why Kubernetes Security Is Non-Negotiable As Kubernetes becomes the backbone of modern cloud-native infrastructure, security is no longer optional—it’s mission-critical . With multiple moving parts like containers, pods, services, nodes, and more, Kuberne...