Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

Bash Script Automation for User and Group Management in Linux

Managing user onboarding in a corporate environment can be challenging, especially with a large influx of new employees. Manually assigning users to directories, groups, and configuring permissions can be time-consuming and error-prone. To streamline this process and reduce workload, I have developed a Bash script that automates these tasks, ensuring efficient onboarding and proper access permissions for each user. This article provides an overview of the Bash script, detailing its functionality and usage for seamless deployment.

*TAKE A LOOK AT THE SCRIPT
*

#!/bin/bash

# Define the input file and log file
input_file="users.txt"
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"

# Check if the input file exists
if [[ ! -f "$input_file" ]]; then
    echo "Error: $input_file not found."
    exit 1
fi

# Create log file if it doesn't exist
sudo touch "$log_file"

# Create password file if it doesn't exist
if [[ ! -f "$password_file" ]]; then
    sudo touch "$password_file"
fi

generate_password() {
    local length="${1:-16}"  # Default length is 16 characters
    openssl rand -base64 12 | tr -dc 'a-zA-Z0-9' | head -c"$length"
}

## Function to log messages
log_message() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | sudo tee -a "$log_file" > /dev/null
}

# Arrays to store usernames and groups
declare -A user_groups
declare -A unique_groups
usernames=()

# Read the input file line by line
while IFS= read -r line || [[ -n "$line" ]]; do
    # Remove leading and trailing whitespace
    line=$(echo "$line" | xargs)

    # Split the line at the semicolon
    username=$(echo "$line" | cut -d ';' -f 1 | xargs)
    group_list=$(echo "$line" | cut -d ';' -f 2 | xargs)

    # Store username
    usernames+=("$username")

    # Store groups for each user
    user_groups["$username"]="$group_list"

    # Split groups by comma and store them in unique_groups
    IFS=',' read -ra group_array <<< "$group_list"
    for group in "${group_array[@]}"; do
        group=$(echo "$group" | xargs)
        unique_groups["$group"]=1  # Use group name as key to ensure uniqueness
    done

**    # Create user and add to groups
**    if sudo getent passwd "$username" &>/dev/null; then
        log_message "User '$username' already exists."
    else
        # Generate random password
        password=$(generate_password 12)  # Adjust password length as needed

        # Store password in file
        echo "$username:$password" | sudo tee -a "$password_file" > /dev/null

        if sudo useradd -m -p "$(openssl passwd -1 "$password")" "$username"; then
            log_message "User '$username' created successfully."

            # Add user to their respective groups
            for group in "${group_array[@]}"; do
                sudo usermod -aG "$group" "$username"
                log_message "User '$username' added to group '$group'."
            done

            # Set permissions for home directory
            sudo chmod 700 "/home/$username"
            sudo chown "$username":"$username" "/home/$username"
            log_message "Home directory permissions set for '$username'."
        else
            log_message "Failed to create user '$username'."
        fi
    fi

done < "$input_file"

# Create groups if they don't exist
for group in "${!unique_groups[@]}"; do
    if sudo getent group "$group" &>/dev/null; then
        log_message "Group '$group' already exists."
    else
        if sudo groupadd "$group"; then
            log_message "Group '$group' created successfully."
        else
            log_message "Failed to create group '$group'."
        fi
    fi
done

*A BREAK DOWN OF THE SCRIPT
*

The Bash script begins by defining crucial variables for file paths and initialization:

#!/bin/bash
input_file="users.txt"
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"

Here, users.txt serves as the input file containing user details, user_management.log is where all actions are logged, and user_passwords.txt is where the generated passwords are securely stored.

*File Validation And Initialization
*

The script ensures the existence of the input file and creates the necessary log and password files if they don't already exist:

if [[ ! -f "$input_file" ]]; then
    echo "Error: $input_file not found."
    exit 1
fi

# Create log file if it doesn't exist
sudo touch "$log_file"

# Create password file if it doesn't exist
if [[ ! -f "$password_file" ]]; then
    sudo touch "$password_file"
fi

**

Function to generate a random password

# Function to generate a random password 
generate_password() {
    local length="${1:-16}"  # Default length is 16 characters
    openssl rand -base64 12 | tr -dc 'a-zA-Z0-9' | head -c"$length"
}

This segment ensures random and unique passwords are generated for each user.

*Logging Messages
*

Another function logs messages to user_management.log, capturing events throughout the script's execution:

Function to log messages

log_message() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | sudo tee -a "$log_file" > /dev/null
}

Here, timestamps are prefixed to each log entry, aiding in tracking and auditing changes made by the script.

User and Group Creation Logic

The core of the script iterates through each line of users.txt, parsing usernames and associated groups, creating users if they don't exist, assigning passwords, and configuring group memberships and permissions:

# Arrays to store usernames and groups

declare -A user_groups
declare -A unique_groups
usernames=()

# Read the input file line by line
while IFS= read -r line || [[ -n "$line" ]]; do
    # Processing each user and their associated groups
    # ...

done < "$input_file"

This loop efficiently handles user creation and group management based on parsed data, ensuring minimal manual intervention and high accuracy.

*Follow the steps below to successfully Run this Script
*

  1. To ensure the script is excutable:

chmod +x create_users.sh

  1. Run the Script with Sudo:

sudo ./create_users.sh

*The Key Files Needed:
*

  1. /var/log/user_management.log: All actions, including successes and errors, are logged here.

  2. /var/secure/user_passwords.txt: Generated passwords are stored securely here with appropriate permissions.

  3. users.txt: Usernames and groups are specified in this file.
    Conclusion

*Conclusion
*

In conclusion, this Bash script exemplifies how automation simplifies complex tasks such as user and group management in Linux environments. By leveraging shell scripting, administrators can achieve consistency, security, and efficiency across system deployments.

For places where you can grow your tech.skills and get hands-on projects, please visit:

https://hng.tech/internship
OR
https://hng.tech/hire

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.