DEV Community

Ayomide
Ayomide

Posted on

HNG STAGE 1 TASK: Linux User Creation Bash Script Task

Introduction

Managing user accounts and groups efficiently is a critical task for any SysOps engineer. It is essential to automate this process to ensure consistency, security, and ease of management. In this article, we will explore a bash script that automates the creation of users and groups based on a provided text file. This script sets up home directories, generates random passwords, and logs all actions performed.

Script Overview
Our bash script, create_users.sh, reads a text file where each line is formatted as username;groups, creates users, assigns them to groups, and logs the actions. The script also handles error scenarios for existing users and sets appropriate permissions for home directories and password files.

Initialization and Variable Declaration

#!/bin/bash

log_message_file="/var/log/user_management.log"
passwords_file="/var/secure/user_passwords.txt"
Enter fullscreen mode Exit fullscreen mode

I defined the log and password files, ensuring they exist.

Fucntion to Verify User and Group

# Check if a user exists
user_exists() {
    local username=$1
    if getent passwd "$username" > /dev/null 2>&1; then
        return 0  # User exists
    else
        return 1  # User does not exist
    fi
}

# Check if a group exists
group_exists() {
    local group_name=$1
    if getent group "$group_name" > /dev/null 2>&1; then
        return 0  # Group exists
    else
        return 1  # Group does not exist
    fi
}
Enter fullscreen mode Exit fullscreen mode

I declare functions to check if the users and groups exists. They will be called in later

Function for Password Generation and Logging

# Generate a random password
generate_password() {
    openssl rand -base64 12
}

# Log actions to /var/log/user_management.log
log() {
    local MESSAGE="$1"
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $MESSAGE" | sudo tee -a $log_message_file > /dev/null
}
Enter fullscreen mode Exit fullscreen mode

The first function generates a random password and the second function sends a log of all actions to the specified file

# Assign the file name from the command line argument
user_group=$1

Enter fullscreen mode Exit fullscreen mode

Here, a variable is assigned to the command line argument as a stand in for the filename

Log and Password File Creation

# Check if the log file exist

if [ ! -f "$log_messsage_file" ]; then
    # Create the log file
    sudo touch "$log_message_file"
    log "$log_message_file has been created."
else
    log "$log_message_file exists already"
fi

# Check and create the passwords_file

if [ ! -f "$passwords_file" ]; then
    # Create the file and set permissions
    sudo mkdir -p /var/secure/
    sudo touch "$passwords_file"
    log "$passwords_file has been created."
    # Set ownership permissions for passwords_file
    sudo chmod 600 "$passwords_file"
    log "Updated passwords_file permission to file owner"
else
    log "$passwords_file exists already"
fi
Enter fullscreen mode Exit fullscreen mode

Here, the log file and password file are checked for any sign of existence and created if none is found

Looping Through Users and Groups

while IFS=';' read -r username groups; do
    # Extract the user name
    username=$(echo "$username" | xargs)
Enter fullscreen mode Exit fullscreen mode

Using IFS, I separate the value in our text file using the ";" as the delimiter and extract the username and groups

Checking for Users and Password Creation

    # Check if the user exists
    if user_exists "$username"; then
        log "$username exists already"
        continue
    else
        # Generate a random password for the user
        password=$(generate_password)

        # Create the user with home directory and set password
        sudo useradd -m -s /bin/bash "$username"
        echo "$username:$password" | sudo chpasswd

        log "Successfully Created User: $username"
    fi

Enter fullscreen mode Exit fullscreen mode

This code checks if the user already exists; otherwise, it creates the user and gives it a randomized password.

Checking for User Group

    # check that the user has its own group
    if ! group_exists "$username"; then
        sudo groupadd "$username"
        log "Successfully created group: $username"
        sudo usermod -aG "$username" "$username"
        log "User: $username added to Group: $username"
    else
        log "User: $username added to Group: $username"
    fi
Enter fullscreen mode Exit fullscreen mode

It checks if the user created has its own group and adds it to its group if it does not.

Extracting The Groups

    # Extract the groups and remove any spaces
    groups=$(echo "$groups" | tr -d ' ')

    # Split the groups by comma
    IFS=',' read -r -a group_count <<< "$groups"
Enter fullscreen mode Exit fullscreen mode

From the text file, we extract the groups, spilt the values by the comma "," delimiter and append the values into the _group_count _array.

Creation of Groups and Attachment of Users

    # Create the groups and add the user to each group
    for group in "${group_count[@]}"; do
        # Check if the group already exists
        if ! group_exists "$group"; then
            # Create the group if it does not exist
            sudo groupadd "$group"
            log "Successfully created Group: $group"
        else
            log "Group: $group already exists"
        fi
        # Add the user to the group
        sudo usermod -aG "$group" "$username"
    done
Enter fullscreen mode Exit fullscreen mode

By looping through the array, we check if the group exists, create it if it does not and add the users to their respective groups

Setting Appropriate Permission

    # Set permissions for home directory
    sudo chmod 700 "/home/$username"
    sudo chown "$username:$username" "/home/$username"
    log "Updated permissions for home directory: '/home/$username' of User: $username to '$username:$username'"
Enter fullscreen mode Exit fullscreen mode

Here, we set the permission and ownership for the home directory of the created user(s)

Storing Username and Password in Password file

    # Store username and password in secure file
    echo "$username,$password" | sudo tee -a "$passwords_file" > /dev/null
    log "Stored username and password in $passwords_file"
done < "$user_group"
Enter fullscreen mode Exit fullscreen mode

Here, we store the user and password in the specified file

To learn more about the HNG internship and what they do, check out HNG Internship. You can also visit HNG Hire to scout the best talents.

Thank You.

Top comments (0)