DEV Community

Lawal Mary
Lawal Mary

Posted on

Automating User and Group Management in Linux with Bash

Managing user accounts and permissions on a Linux system can be a daunting task, especially in a dynamic environment with frequent new hires. To simplify and automate this process, we have created the create_users.sh script. This Bash script reads user and group information from a file, creates users and groups, sets up home directories, generates random passwords, and logs all actions.

In this article, we'll walk you through how the script works and how to use it effectively. This guide is particularly useful for SysOps engineers looking to streamline user management in their systems.

For those interested in pursuing or learning more about technical roles and internships, the HNG Internship Program offers an excellent opportunity to enhance your skills and experience.

Understanding the create_users.sh Script

Key Features

  • Automated User Creation: Reads user information from a text file and creates users accordingly.
  • Group Management: Ensures each user has a personal group with the same name and adds users to specified additional groups.
  • Home Directory Setup: Creates and configures home directories with secure permissions.
  • Password Generation: Generates random passwords for new users and stores them securely.
  • Logging: Logs all actions and errors for easy monitoring and troubleshooting.

Input File Format
The input file should list users and their groups in the following format:

  1. username; group1,group2,group3
  2. Each line represents one user
  3. The username and groups are separated by a semicolon ;.
  4. Groups are optional and can be separated by commas ,.

Example Input:
_light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data_

In this example:
light will be created with additional groups sudo, dev, and www-data.
idimma will be added to the sudo group.
mayowa will join the dev and www-data groups.

Script Details

Here is the complete create_users.sh script:
`#!/bin/bash

# File paths
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
# Ensure /var/secure directory exists
if ! mkdir -p /var/secure 2>/dev/null; then
    echo "Failed to create /var/secure directory. Permission denied."
    exit 1
fi
chmod 700 /var/secure
# Clear log and password files
> "$LOG_FILE" 2>/dev/null || { echo "Failed to create log file $LOG_FILE. Permission denied."; exit 1; }
> "$PASSWORD_FILE" 2>/dev/null || { echo "Failed to create password file $PASSWORD_FILE. Permission denied."; exit 1; }
chmod 600 "$PASSWORD_FILE"
# Function to generate a random password
generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
# Check if input file is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <user_list_file>"
    exit 1
fi
# Read the input file line by line
while IFS=';' read -r username groups; do
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

    if id "$username" &>/dev/null; then
        echo "User $username already exists. Skipping..." | tee -a "$LOG_FILE"
        continue
    fi
    # Create personal group with the same name as the user
    if ! getent group "$username" &>/dev/null; then
        if ! groupadd "$username" 2>/dev/null; then
            echo "Failed to create group $username. Permission denied." | tee -a "$LOG_FILE"
            continue
        fi
        echo "Group $username created." | tee -a "$LOG_FILE"
    fi
    # Create the user with the personal group
    if ! useradd -m -g "$username" -s /bin/bash "$username" 2>/dev/null; then
        echo "Failed to create user $username. Permission denied." | tee -a "$LOG_FILE"
        continue
    fi
    echo "User $username created with home directory." | tee -a "$LOG_FILE"
    # Add user to additional groups
    IFS=',' read -ra ADDR <<< "$groups"
    for group in "${ADDR[@]}"; do
        group=$(echo "$group" | xargs)
        if ! getent group "$group" &>/dev/null; then
            if ! groupadd "$group" 2>/dev/null; then
                echo "Failed to create group $group. Permission denied." | tee -a "$LOG_FILE"
                continue
            fi
            echo "Group $group created." | tee -a "$LOG_FILE"
        fi
        if ! usermod -aG "$group" "$username" 2>/dev/null; then
            echo "Failed to add user $username to group $group. Permission denied." | tee -a "$LOG_FILE"
            continue
        fi
        echo "User $username added to group $group." | tee -a "$LOG_FILE"
    done
    # Set up home directory permissions
    chmod 700 "/home/$username"
    chown "$username:$username" "/home/$username"
    # Generate a random password and set it for the user
    password=$(generate_password)
    echo "$username:$password" | chpasswd 2>/dev/null || { echo "Failed to set password for user $username. Permission denied."; continue; }
    # Log the password securely
    echo "$username,$password" >> "$PASSWORD_FILE"
    echo "Password for user $username set." | tee -a "$LOG_FILE"
done < "$1"
echo "User creation process completed." | tee -a "$LOG_FILE"
Enter fullscreen mode Exit fullscreen mode

`
Step-by-Step ExplanationInitialization and Setup:

 The script starts by defining paths for the log and password files.
It ensures these files exist and sets secure permissions on the password file to make it readable only by the owner.

Functions:

  1. generate_password: Generates a 12-character random password.
  2. log_message: Logs messages with a timestamp to both the console and the log file.
  3. Input Validation: The script checks if an input file is provided and verifies its existence and readability.
  4. Processing Each User: The script reads each line of the input file, splits it into a username and groups, and trims any whitespace. It skips empty username entries and checks if the user already exists.
  5. User and Group Creation: If the user does not exist, it creates a personal group with the same name. It creates the user with a home directory and assigns the personal group.
  6. Home Directory Setup: The script sets secure permissions (700) on the user's home directory and changes ownership to the user.
  7. Password Management: It generates a random password for each user.
  8. Logging: All actions and errors are logged to /var/log/user_management.log. 

Using the Script
To use the script, follow these steps

  • Save the Script: Save the provided script as create_users.sh.
  • Make the Script Executable: chmod +x create_users.sh
  • Prepare Your Input File: Create a text file with usernames and groups in the required format.
    Example:
    _light; sudo,dev,www-data
    idimma; sudo
    mayowa; dev,www-data_

  • Run the Script: sudo ./create_users.sh input_file.txt

Conclusion
The create_users.sh script provides an efficient and automated way to manage user accounts in Linux. It handles user and group creation, home directory setup, password generation, and logs all actions for easy monitoring and troubleshooting. This script is a valuable tool for SysOps engineers looking to streamline their user management processes.

Learn about HNG internship

This article is task 2 in the devops track of HNG Internship. For those interested in further developing their skills and gaining real-world experience, consider exploring the HNG Internship Program via this link  https://hng.tech/internship. This program offers a range of opportunities to work on challenging projects and collaborate with professionals in the field.

For organizations looking to hire top talent from the HNG Internship, you can find more information on https://hng.tech/hire.

Top comments (0)