DEV Community

Cover image for Automating User Management with a Bash Script
Phoenix
Phoenix

Posted on • Edited on

Automating User Management with a Bash Script

Managing users in a Linux environment can be a daunting task, especially when your organization grows rapidly. As a DevOps engineer, having an automated process to handle user creation, group assignments, and password generation can save a significant amount of time and reduce errors. In this article, I'll walk you through a bash script designed to streamline user management by reading a file containing usernames and groups, creating the necessary users and groups, setting up home directories, and logging all actions.

The Challenge
When new developers join your team, it's essential to ensure they have the necessary access and permissions. Manually creating each user, assigning them to the appropriate groups, and setting up their home directories can be error-prone and time-consuming. To solve this, we'll create a bash script that automates this process.

The Solution
Our script, create_users.sh, will:

  • Read a text file containing usernames and group names.
  • Create users and groups as specified.
  • Set up home directories with appropriate permissions.
  • Generate random passwords for the users.
  • Log all actions to /var/log/user_management.log.
  • Store the generated passwords securely in /var/secure/user_passwords.csv.

Let's dive into the script.

The Script
Here's the complete create_users.sh script:

#!/bin/bash

# Logging and password storage files
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Ensure the secure directory exists
mkdir -p /var/secure

# Ensure the log file exists and create it if it doesn't
touch $LOG_FILE

# Ensure the password file exists and set the correct permissions
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

# Combined log and echo function
log_and_echo() {
    message="$(date +'%Y-%m-%d %H:%M:%S') - $1"
    echo $message
    echo $message >> $LOG_FILE
}

# Function to generate random passwords
generate_password() {
    tr -dc 'A-Za-z0-9' </dev/urandom | head -c 12
}

# Check if a file was provided
if [ -z "$1" ]; then
    echo "Usage: bash create_users.sh <name-of-text-file>"
    exit 1
fi

# Read the file line by line
while IFS=';' read -r username groups; do
    # Remove leading/trailing whitespaces
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)

    # Skip empty lines
    if [ -z "$username" ]; then
        continue
    fi

    log_and_echo "Processing user: $username"

    # Check if user already exists
    if id -u "$username" >/dev/null 2>&1; then
        log_and_echo "User $username already exists. Skipping creation."
        continue
    fi

    # Create a user-specific group if it doesn't exist
    if ! getent group "$username" >/dev/null 2>&1; then
        groupadd "$username"
        log_and_echo "Group $username created."
    fi

    # Create the user with the specific group
    useradd -m -g "$username" "$username" && log_and_echo "User $username created with primary group $username."

    # Assign additional groups
    IFS=',' read -ra additional_groups <<< "$groups"
    for group in "${additional_groups[@]}"; do
        group=$(echo $group | xargs)  # Remove leading/trailing whitespaces
        if [ -n "$group" ] && ! getent group "$group" >/dev/null 2>&1; then
            groupadd "$group"
            log_and_echo "Group $group created."
        fi
        usermod -aG "$group" "$username" && log_and_echo "User $username added to group $group."
    done

    # Generate a random password
    password=$(generate_password)

    # Set the user's password
    echo "$username:$password" | chpasswd && log_and_echo "Password set for user $username."

    # Store the username and password securely
    echo "$username,$password" >> $PASSWORD_FILE

    # Set home directory permissions
    chmod 700 "/home/$username" && log_and_echo "Permissions set for user $username's home directory."

done < "$1"

log_and_echo "User creation process completed."
echo "User creation process completed."


Enter fullscreen mode Exit fullscreen mode

How It Works

  • Setup: The script initializes logging and password storage files, ensuring the secure directory and files exist with appropriate permissions.
  • Password Generation: A function generates random 12-character passwords for new users.
  • Logging: All actions are logged with timestamps for auditing purposes.
  • Input Validation: The script checks if a valid input file is provided and ensures the log file exists.
  • Processing: The script reads the input file line by line, creating users and groups as specified, and handling any existing users or groups appropriately.
  • Home Directory Permissions: The home directory for each user is created with secure permissions.
  • Final Log: A final message is logged once the user creation process is completed.

Usage

  1. Prepare the Input File: Create a text file named users.txt with the following content:
light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
john; admin,dev
Enter fullscreen mode Exit fullscreen mode
  1. Run the Script: Make the script executable and run it with sudo to ensure it has the necessary permissions:
chmod +x create_users.sh
sudo ./create_users.sh users.txt

Enter fullscreen mode Exit fullscreen mode
  1. Verifying the Results
  • Check the Log File:
    cat /var/log/user_management.log

  • Check the Password File:

sudo cat /var/secure/user_passwords.csv

  • Verify Users and Groups:
getent passwd light
getent group light
getent group sudo

Enter fullscreen mode Exit fullscreen mode

Conclusion
Automating user management in a Linux environment can significantly improve efficiency and reduce errors. By leveraging a bash script like create_users.sh, you can quickly and securely create users, assign groups, and set up home directories. This script ensures that all actions are logged and passwords are stored securely, making it a valuable tool for any DevOps engineer.

To learn more about the HNG Internship and explore opportunities, visit:

Top comments (1)