Linux User Management

Complete guide to managing users and groups in Linux systems. Learn user account creation, group management, permissions, sudo configuration, and security best practices.

Overview

User management is a fundamental aspect of Linux system administration. It involves creating, modifying, and deleting user accounts, managing groups, setting permissions, and configuring access controls. Proper user management ensures system security, resource allocation, and organized access control.

Key Components
  • User Accounts - Individual user identities with unique UIDs
  • Groups - Collections of users for permission management
  • Home Directories - Personal file spaces for users
  • Shell Access - Command-line interface configuration
  • Sudo Access - Administrative privilege delegation

User Account Management

Creating users

# Create basic user account sudo useradd username # Create user with home directory and shell sudo useradd -m -s /bin/bash username # Create user with specific UID and GID sudo useradd -u 1001 -g 1001 -m username # Create user with additional groups sudo useradd -m -G sudo,docker username # Create system user (no home directory) sudo useradd -r -s /bin/false serviceuser

Create new user accounts with various options and configurations

Setting passwords

# Set password for user sudo passwd username # Force password change on next login sudo passwd -e username # Lock user account sudo passwd -l username # Unlock user account sudo passwd -u username # Check password status sudo passwd -S username

Manage user passwords and account status

Modifying users

# Change user's home directory sudo usermod -d /new/home/path username # Change user's shell sudo usermod -s /bin/zsh username # Add user to group sudo usermod -aG groupname username # Change user's primary group sudo usermod -g newgroup username # Lock user account sudo usermod -L username # Unlock user account sudo usermod -U username # Change username sudo usermod -l newname oldname

Modify existing user account properties

Deleting users

# Delete user (keep home directory) sudo userdel username # Delete user and home directory sudo userdel -r username # Force delete user (even if logged in) sudo userdel -f username # Delete user and backup home directory sudo userdel -r --backup-to /backup/users username

Remove user accounts from the system

Group Management

Creating groups

# Create new group sudo groupadd groupname # Create group with specific GID sudo groupadd -g 2000 groupname # Create system group sudo groupadd -r systemgroup # Force create group (override existing) sudo groupadd -f groupname

Create new groups for organizing users

Managing group membership

# Add user to group sudo usermod -aG groupname username # Add multiple users to group sudo gpasswd -M user1,user2,user3 groupname # Remove user from group sudo gpasswd -d username groupname # Set group administrators sudo gpasswd -A admin1,admin2 groupname # Change group password sudo gpasswd groupname

Manage users within groups

Modifying groups

# Change group name sudo groupmod -n newname oldname # Change group GID sudo groupmod -g 3000 groupname # Delete group sudo groupdel groupname # Force delete group (even if it's primary group) sudo groupdel -f groupname

Modify and delete existing groups

User Information and Monitoring

Viewing user information

# Show current user whoami # Show user ID information id username # Show all users cat /etc/passwd # Show user details getent passwd username # Show groups for user groups username # Show all groups cat /etc/group # Show logged in users who w # Show last login information last username lastlog

Display user and group information

User activity monitoring

# Show currently logged in users users # Show detailed user activity w # Show login history last # Show failed login attempts lastb # Show user login times lastlog # Show system uptime and load uptime # Monitor user processes ps aux | grep username

Monitor user activity and system usage

Sudo Configuration

Basic sudo setup

# Add user to sudo group sudo usermod -aG sudo username # Edit sudoers file safely sudo visudo # Test sudo configuration sudo -l # Run command as another user sudo -u username command # Run command as root sudo command # Switch to root shell sudo -i sudo su -

Configure sudo access for users

Sudoers file examples

# Allow user to run all commands username ALL=(ALL:ALL) ALL # Allow user to run commands without password username ALL=(ALL) NOPASSWD: ALL # Allow user to run specific commands username ALL=(ALL) /bin/systemctl, /usr/bin/apt # Allow group to run all commands %groupname ALL=(ALL:ALL) ALL # Allow user to run commands as specific user username ALL=(webuser) ALL # Restrict to specific hosts username hostname=(ALL) ALL # Command aliases Cmnd_Alias SERVICES = /bin/systemctl start, /bin/systemctl stop username ALL=(ALL) SERVICES

Configure detailed sudo permissions in /etc/sudoers

Sudo security options

# Require password for sudo Defaults timestamp_timeout=15 # Log sudo commands Defaults logfile="/var/log/sudo.log" # Require TTY for sudo Defaults requiretty # Set secure path Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" # Disable root login Defaults !rootpw # Set password timeout Defaults passwd_timeout=5

Configure sudo security settings

File Permissions and Ownership

Changing ownership

# Change file owner sudo chown username file.txt # Change owner and group sudo chown username:groupname file.txt # Change ownership recursively sudo chown -R username:groupname directory/ # Change only group sudo chgrp groupname file.txt # Change group recursively sudo chgrp -R groupname directory/ # Copy ownership from another file sudo chown --reference=source.txt target.txt

Change file and directory ownership

Setting permissions

# Set permissions using octal notation chmod 755 file.txt # rwxr-xr-x chmod 644 file.txt # rw-r--r-- chmod 600 file.txt # rw------- # Set permissions using symbolic notation chmod u+x file.txt # Add execute for user chmod g-w file.txt # Remove write for group chmod o=r file.txt # Set read-only for others chmod a+r file.txt # Add read for all # Set permissions recursively chmod -R 755 directory/ # Set default permissions umask 022 # Default: 755 for dirs, 644 for files

Configure file and directory permissions

Special permissions

# Set sticky bit (only owner can delete) chmod +t directory/ chmod 1755 directory/ # Set setuid bit (run as owner) chmod u+s executable chmod 4755 executable # Set setgid bit (run as group) chmod g+s executable chmod 2755 executable # Combine special permissions chmod 6755 executable # setuid + setgid chmod 7755 directory/ # setuid + setgid + sticky # View special permissions ls -l file

Configure special permission bits

User Environment Configuration

Shell configuration

# Change user's default shell sudo chsh -s /bin/zsh username # List available shells cat /etc/shells # User changes own shell chsh # Set shell for new users sudo useradd -s /bin/bash newuser # Verify user's shell getent passwd username | cut -d: -f7

Configure user shell environments

Home directory setup

# Create home directory sudo mkdir /home/username sudo chown username:username /home/username # Copy skeleton files sudo cp -r /etc/skel/. /home/username/ sudo chown -R username:username /home/username # Set home directory permissions sudo chmod 755 /home/username # Move home directory sudo usermod -d /new/home/path -m username # Create user with custom home sudo useradd -m -d /custom/path username

Set up and manage user home directories

Environment variables

# System-wide environment sudo nano /etc/environment # User-specific environment nano ~/.bashrc nano ~/.profile # Set PATH for user echo 'export PATH=$PATH:/custom/bin' >> ~/.bashrc # Set custom variables echo 'export CUSTOM_VAR=value' >> ~/.bashrc # Reload environment source ~/.bashrc # View environment env printenv

Configure user environment variables

Account Security and Policies

Password policies

# Install password quality tools sudo apt install libpam-pwquality # Configure password policy sudo nano /etc/pam.d/common-password # Set password aging sudo chage -M 90 username # Max 90 days sudo chage -m 7 username # Min 7 days sudo chage -W 7 username # Warn 7 days before # View password aging info sudo chage -l username # Force password change sudo chage -d 0 username # Set account expiration sudo chage -E 2024-12-31 username

Configure password policies and aging

Account locking and security

# Lock user account sudo usermod -L username sudo passwd -l username # Unlock user account sudo usermod -U username sudo passwd -u username # Set account expiration sudo usermod -e 2024-12-31 username # Disable account (set shell to nologin) sudo usermod -s /usr/sbin/nologin username # Check failed login attempts sudo faillog -u username # Reset failed login count sudo faillog -r -u username

Implement account security measures

SSH key management

# Generate SSH key pair ssh-keygen -t rsa -b 4096 -C "[email protected]" # Copy public key to server ssh-copy-id username@server # Manual key installation mkdir -p ~/.ssh chmod 700 ~/.ssh cat id_rsa.pub >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys # Disable password authentication sudo nano /etc/ssh/sshd_config # PasswordAuthentication no sudo systemctl restart sshd # Restrict SSH access # AllowUsers username1 username2 # DenyUsers baduser

Configure SSH key authentication and access control

Practical Examples

Web server user setup

# Create web server user sudo useradd -r -s /bin/false -d /var/www -c "Web Server User" www-data # Create web developers group sudo groupadd webdev # Add developers to group sudo usermod -aG webdev alice sudo usermod -aG webdev bob # Set web directory permissions sudo chown -R www-data:webdev /var/www sudo chmod -R 775 /var/www # Set sticky bit for collaboration sudo chmod g+s /var/www

Set up users and permissions for web development

Database user configuration

# Create database user sudo useradd -r -s /bin/false -d /var/lib/mysql mysql # Create database admin group sudo groupadd dbadmin # Add DBA users to group sudo usermod -aG dbadmin dba1 sudo usermod -aG dbadmin dba2 # Configure sudo for database commands echo "%dbadmin ALL=(mysql) NOPASSWD: /usr/bin/mysql, /usr/bin/mysqldump" | sudo tee /etc/sudoers.d/dbadmin # Set database directory permissions sudo chown -R mysql:mysql /var/lib/mysql sudo chmod 750 /var/lib/mysql

Configure users for database administration

Service account setup

# Create service account sudo useradd -r -s /bin/false -d /opt/myapp myapp # Create service directory sudo mkdir -p /opt/myapp sudo chown myapp:myapp /opt/myapp # Create systemd service sudo tee /etc/systemd/system/myapp.service << EOF [Unit] Description=My Application After=network.target [Service] Type=simple User=myapp Group=myapp WorkingDirectory=/opt/myapp ExecStart=/opt/myapp/start.sh Restart=always [Install] WantedBy=multi-user.target EOF # Enable and start service sudo systemctl enable myapp sudo systemctl start myapp

Create dedicated service accounts for applications

Troubleshooting User Issues

Common Problems
  • Permission denied - Check file ownership and permissions
  • User cannot login - Check account status and shell
  • Sudo not working - Verify group membership and sudoers configuration
  • Home directory issues - Check ownership and permissions
  • Group membership problems - Use id command to verify groups

Diagnostic commands

# Check user account status sudo passwd -S username sudo chage -l username # Verify user information id username getent passwd username groups username # Check file permissions ls -la /home/username namei -l /path/to/file # Test sudo access sudo -l -U username # Check login attempts sudo lastlog -u username sudo faillog -u username # Verify group membership getent group groupname # Check system logs sudo journalctl -u ssh sudo tail /var/log/auth.log

Commands for diagnosing user-related issues

Recovery procedures

# Reset user password sudo passwd username # Unlock locked account sudo usermod -U username sudo passwd -u username # Fix home directory ownership sudo chown -R username:username /home/username sudo chmod 755 /home/username # Restore default shell sudo usermod -s /bin/bash username # Reset failed login attempts sudo faillog -r -u username # Fix sudo access sudo usermod -aG sudo username # Recreate home directory sudo mkdir /home/username sudo cp -r /etc/skel/. /home/username/ sudo chown -R username:username /home/username

Common recovery procedures for user account issues

User Management Best Practices

Security Best Practices
  • Use strong password policies and enforce regular changes
  • Implement principle of least privilege
  • Regularly audit user accounts and remove unused accounts
  • Use SSH keys instead of passwords for remote access
  • Monitor user activity and login attempts
  • Separate administrative and regular user accounts
Organizational Best Practices
  • Use consistent naming conventions for users and groups
  • Document user roles and responsibilities
  • Implement proper onboarding and offboarding procedures
  • Use groups for permission management instead of individual users
  • Maintain backup of user data and configurations
  • Regular review of user permissions and access rights
Common Mistakes to Avoid
  • Using root for daily tasks - Always use regular accounts with sudo
  • Weak passwords - Enforce strong password policies
  • Shared accounts - Each person should have individual accounts
  • Excessive permissions - Grant minimum necessary permissions
  • Forgotten accounts - Regular audit and cleanup of unused accounts
  • No backup strategy - Backup user data and configurations

User Management Automation

User creation script

#!/bin/bash # Automated user creation script create_user() { local username="$1" local fullname="$2" local groups="$3" # Validate input if [[ -z "$username" ]]; then echo "Error: Username required" return 1 fi # Check if user exists if id "$username" &>/dev/null; then echo "Error: User $username already exists" return 1 fi # Create user sudo useradd -m -s /bin/bash -c "$fullname" "$username" # Add to groups if [[ -n "$groups" ]]; then sudo usermod -aG "$groups" "$username" fi # Set password echo "Setting password for $username" sudo passwd "$username" # Set password aging sudo chage -M 90 -m 7 -W 7 "$username" echo "User $username created successfully" } # Usage create_user "jdoe" "John Doe" "sudo,docker"

Automated user creation with standard configuration

User audit script

#!/bin/bash # User account audit script echo "=== User Account Audit Report ===" echo "Generated on: $(date)" echo # System users (UID < 1000) echo "=== System Users ===" awk -F: '$3 < 1000 {print $1 ":" $3 ":" $7}' /etc/passwd | column -t -s: echo # Regular users (UID >= 1000) echo "=== Regular Users ===" awk -F: '$3 >= 1000 {print $1 ":" $3 ":" $5 ":" $7}' /etc/passwd | column -t -s: echo # Users with sudo access echo "=== Users with Sudo Access ===" getent group sudo | cut -d: -f4 | tr ',' '\n' echo # Locked accounts echo "=== Locked Accounts ===" sudo passwd -Sa | grep -E "L|NP" | awk '{print $1 " - " $2}' echo # Users with no password echo "=== Users with No Password ===" sudo passwd -Sa | grep "NP" | awk '{print $1}' echo # Recently logged in users echo "=== Recent Logins (Last 7 days) ===" last -t $(date -d '7 days ago' +%Y%m%d%H%M%S) | head -20 echo # Users with expired passwords echo "=== Users with Expired Passwords ===" for user in $(awk -F: '$3 >= 1000 {print $1}' /etc/passwd); do if sudo chage -l "$user" 2>/dev/null | grep -q "Password expires.*in the past"; then echo "$user" fi done

Comprehensive user account audit and reporting

Bulk user management

#!/bin/bash # Bulk user management script # CSV format: username,fullname,groups,email USER_FILE="users.csv" bulk_create_users() { if [[ ! -f "$USER_FILE" ]]; then echo "Error: User file $USER_FILE not found" return 1 fi while IFS=',' read -r username fullname groups email; do # Skip header line [[ "$username" == "username" ]] && continue echo "Creating user: $username" # Create user sudo useradd -m -s /bin/bash -c "$fullname" "$username" # Add to groups if [[ -n "$groups" ]]; then sudo usermod -aG "$groups" "$username" fi # Generate random password password=$(openssl rand -base64 12) echo "$username:$password" | sudo chpasswd # Force password change on first login sudo chage -d 0 "$username" # Log credentials (secure this file!) echo "$username:$password:$email" >> user_credentials.txt echo "User $username created with temporary password" done < "$USER_FILE" echo "Bulk user creation completed" echo "Credentials saved to user_credentials.txt" } bulk_delete_users() { local user_list="$1" if [[ ! -f "$user_list" ]]; then echo "Error: User list file not found" return 1 fi while read -r username; do if id "$username" &>/dev/null; then echo "Deleting user: $username" sudo userdel -r "$username" else echo "User $username not found" fi done < "$user_list" } # Usage examples # bulk_create_users # bulk_delete_users "users_to_delete.txt"

Bulk user creation and deletion from CSV files

See also