DEV Community

Cover image for Automating User Creation and Management with a Bash Script
Kenneth Mahon
Kenneth Mahon

Posted on

Automating User Creation and Management with a Bash Script

In this article, we'll walk through a bash script that reads user information from a text file, creates users and their groups, sets up home directories, generates random passwords, logs actions, and stores passwords securely.

Bash Script: create_users.sh

#!/bin/bash

# Define file paths
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
INPUT_FILE=$1

# Ensure secure directory for passwords
mkdir -p /var/secure
chmod 700 /var/secure

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

# Ensure log file exists
touch $LOG_FILE
chmod 644 $LOG_FILE

# Ensure password file exists
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

# Read input file
if [[ ! -f "$INPUT_FILE" ]]; then
    echo "Input file not found!" | tee -a $LOG_FILE
    exit 1
fi

# Process each line in the input file
while IFS=";" read -r username groups; do
    # Trim whitespaces
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)

    # Check if user already exists
    if id -u "$username" >/dev/null 2>&1; then
        echo "User $username already exists. Skipping." | tee -a $LOG_FILE
        continue
    fi

    # Create personal group for the user
    groupadd "$username"

    # Create user with personal group
    useradd -m -g "$username" "$username"
    if [[ $? -ne 0 ]]; then
        echo "Failed to create user $username." | tee -a $LOG_FILE
        continue
    fi

    # Create additional groups and add user to them
    IFS=',' read -ra ADDR <<< "$groups"
    for group in "${ADDR[@]}"; do
        group=$(echo $group | xargs)
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
        fi
        usermod -aG "$group" "$username"
    done

    # Generate random password and set it
    password=$(generate_password)
    echo "$username:$password" | chpasswd

    # Log user creation
    echo "Created user $username with groups $groups." | tee -a $LOG_FILE
    echo "$username,$password" >> $PASSWORD_FILE
done < "$INPUT_FILE"

echo "User creation process completed." | tee -a $LOG_FILE

Enter fullscreen mode Exit fullscreen mode

When working as a SysOps engineer, managing user accounts and groups is a routine but crucial task. Automating this process not only saves time but also reduces the potential for errors.

Features:
1.Input File Processing
: The script takes a text file where each line contains a username and a list of groups, separated by a semicolon (;). Example:

light;sudo,dev,www-data
idimma;sudo
mayowa;dev,www-data

2.User and Group Creation: For each user, the script creates a personal group with the same name as the username and adds the user to the specified groups.

3.Home Directory Setup: Home directories are created automatically with appropriate permissions.

4.Random Password Generation: A secure random password is generated for each user.

5.Logging Actions: All actions performed by the script are logged to /var/log/user_management.log

6.Secure Password Storage: Usernames and passwords are stored in /var/secure/user_passwords.txt with restricted access permissions.

Script Breakdown:

1.File Paths and Secure Directory Setup:

LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
INPUT_FILE=$1
mkdir -p /var/secure
chmod 700 /var/secure

Enter fullscreen mode Exit fullscreen mode

2.Random Password Generation Function:

generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}

Enter fullscreen mode Exit fullscreen mode

3._Log and Password File Initialization:
_

touch $LOG_FILE
chmod 644 $LOG_FILE
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

Enter fullscreen mode Exit fullscreen mode

4.Processing the Input File:

if [[ ! -f "$INPUT_FILE" ]]; then
    echo "Input file not found!" | tee -a $LOG_FILE
    exit 1
fi

while IFS=";" read -r username groups; do
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)

    if id -u "$username" >/dev/null 2>&1; then
        echo "User $username already exists. Skipping." | tee -a $LOG_FILE
        continue
    fi

    groupadd "$username"

    useradd -m -g "$username" "$username"
    if [[ $? -ne 0 ]]; then
        echo "Failed to create user $username." | tee -a $LOG_FILE
        continue
    fi

    IFS=',' read -ra ADDR <<< "$groups"
    for group in "${ADDR[@]}"; do
        group=$(echo $group | xargs)
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
        fi
        usermod -aG "$group" "$username"
    done

    password=$(generate_password)
    echo "$username:$password" | chpasswd

    echo "Created user $username with groups $groups." | tee -a $LOG_FILE
    echo "$username,$password" >> $PASSWORD_FILE
done < "$INPUT_FILE"

echo "User creation process completed." | tee -a $LOG_FILE

Enter fullscreen mode Exit fullscreen mode

This script ensures efficient user management and enhances security through automated processes. For more insights, explore further learning opportunities, check out the HNG Internship and HNG Premium website. You won't regret it

Top comments (0)