HNG STAGE 1 TASK: Linux User Creation Bash Script Task
Published: 2024-07-06 11:19:24

**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"
```
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
}
```
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
}
```
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

```
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
```
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)
```
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

```
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
```
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"
```
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
```
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'"
```
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"
```
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](https://hng.tech/internship). You can also visit [HNG Hire](https://hng.tech/hire) to scout the best talents.
 
Thank You.