User account creation using BASH
Published: 2024-07-04 15:26:47

Introduction
In today's fast-paced development environments, automation is key to managing system operations efficiently. As a SysOps engineer, automating the process of creating user accounts, setting up their groups, and managing passwords can save a significant amount of time and reduce errors. This guide walks you through a Bash script designed to automate these tasks, providing detailed explanations for each step.



The Script
The script, create_users.sh, performs the following tasks:

Reads a text file containing usernames and group names.
Creates users and assigns them to specified groups.
Sets up home directories with appropriate permissions.
Generates random passwords for the users.
Logs all actions to /var/log/user_management.log.
Stores generated passwords securely in /var/secure/user_passwords.csv.

```
#!/bin/bash

# Log file
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Check if the text file is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <name-of-text-file>"
    exit 1
fi

# Check if the file exists
if [ ! -f "$1" ]; then
    echo "File $1 does not exist."
    exit 1
fi

# Create necessary directories and files
mkdir -p /var/secure
touch $LOG_FILE
touch $PASSWORD_FILE

# Set permissions for the password file
chmod 600 $PASSWORD_FILE

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

# Read the file line by line
while IFS=';' read -r user groups; do
    # Remove whitespace
    user=$(echo "$user" | xargs)
    groups=$(echo "$groups" | xargs)

    # Check if the user already exists
    if id "$user" &>/dev/null; then
        echo "User $user already exists. Skipping password setting." | tee -a $LOG_FILE
        continue
    fi

    # Create the user's personal group if it doesn't exist
    if ! getent group "$user" >/dev/null; then
        groupadd "$user"
        echo "Group $user created." | tee -a $LOG_FILE
    fi

    # Create the user and assign the personal group as their primary group
    useradd -m -g "$user" "$user"
    if [ $? -eq 0 ]; then
        echo "User $user created successfully." | tee -a $LOG_FILE
    else
        echo "Failed to create user $user." | tee -a $LOG_FILE
        continue
    fi

    # Add the user to additional groups
    if [ -n "$groups" ]; then
        IFS=',' read -ra group_array <<< "$groups"
        for group in "${group_array[@]}"; do
            group=$(echo "$group" | xargs)
            if ! getent group "$group" >/dev/null; then
                groupadd "$group"
                echo "Group $group created." | tee -a $LOG_FILE
            fi
            usermod -aG "$group" "$user"
            echo "User $user added to group $group." | tee -a $LOG_FILE
        done
    fi

    # Generate a random password
    password=$(generate_password)
    echo "$user:$password" | chpasswd

    # Store the password securely
    echo "$user,$password" >> $PASSWORD_FILE
    echo "Password for user $user set and stored securely." | tee -a $LOG_FILE

done < "$1"

echo "User creation process completed. Check $LOG_FILE for details."

```

Explanation
Log and Password Files

The script maintains a log file to record all actions and a password file to store generated passwords securely.

```
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

```

Input Validation

Ensuring the script is provided with the correct input is crucial for its operation.

```
if [ -z "$1" ]; then
    echo "Usage: $0 <name-of-text-file>"
    exit 1
fi

if [ ! -f "$1" ]; then
    echo "File $1 does not exist."
    exit 1
fi

```
Directory and File Creation

Creating necessary directories and setting permissions for secure operations.

```
mkdir -p /var/secure
touch $LOG_FILE
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

```
Generate Password Function

A simple function to generate random passwords.
`generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
`

User and Group Management

The core logic to create users, assign groups, and handle existing users gracefully.

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

    if id "$user" &>/dev/null; then
        echo "User $user already exists. Skipping password setting." | tee -a $LOG_FILE
        continue
    fi

    if ! getent group "$user" >/dev/null; then
        groupadd "$user"
        echo "Group $user created." | tee -a $LOG_FILE
    fi

    useradd -m -g "$user" "$user"
    if [ $? -eq 0 ]; then
        echo "User $user created successfully." | tee -a $LOG_FILE
    else
        echo "Failed to create user $user." | tee -a $LOG_FILE
        continue
    fi

    if [ -n "$groups" ]; then
        IFS=',' read -ra group_array <<< "$groups"
        for group in "${group_array[@]}"; do
            group=$(echo "$group" | xargs)
            if ! getent group "$group" >/dev/null; then
                groupadd "$group"
                echo "Group $group created." | tee -a $LOG_FILE
            fi
            usermod -aG "$group" "$user"
            echo "User $user added to group $group." | tee -a $LOG_FILE
        done
    fi

    password=$(generate_password)
    echo "$user:$password" | chpasswd
    echo "$user,$password" >> $PASSWORD_FILE
    echo "Password for user $user set and stored securely." | tee -a $LOG_FILE

done < "$1"

```
Conclusion
Automating user management tasks using Bash scripts can significantly improve efficiency and accuracy in system operations. This guide and the accompanying script provide a robust solution for user creation, group assignment, and secure password management.

For more information on DevOps and automation, check out these resources:

[HNG Internship](https://hng.tech/internship)
[HNG Hire](https://hng.tech/)
By following these steps, you can ensure a streamlined process for managing users in your development environment.

link to my github: https://github.com/Gbenga001/user_account_automation_with_bash