Automating User Creation and Management with a Bash Script

gbenga700

Gbenga Ojo-Samuel

Posted on July 2, 2024

Automating User Creation and Management with a Bash Script

Introduction

Managing users on a Linux system can be a daunting task, especially in environments where you need to create multiple users, assign them to specific groups, and ensure they have secure passwords. This blog will walk you through a Bash script that automates the process of user creation, group assignment, password generation, and logging. This script is particularly useful for system administrators looking to streamline user management.

The Script

The script, named create_users.sh, reads a text file containing usernames and group names, creates the users, assigns them to the specified groups, sets up their home directories with the appropriate permissions, generates random passwords, and logs all actions.

Step-by-Step Breakdown

Here’s a detailed explanation of what the script does:

1.** Script Initialization:** The script starts by checking if an input file is provided as an argument. It sets the INPUT_FILE variable to the provided argument and defines the log file and password file paths.

#!/bin/bash

# Check if the input file is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <input_file>"
    exit 1
fi

INPUT_FILE=$1
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
Enter fullscreen mode Exit fullscreen mode
  1. File Existence and Directory Setup : The script checks if the input file exists. It then ensures the secure directory (/var/secure) exists, creates the log and password files, and sets appropriate permissions and ownership to ensure security.
# Check if the file exists
if [ ! -f "$INPUT_FILE" ]; then
    echo "File not found: $INPUT_FILE"
    exit 1
fi

# Ensure the secure directory exists and set permissions
sudo mkdir -p /var/secure
sudo chmod 700 /var/secure

# Initialize log and password files
sudo touch $LOG_FILE $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
sudo chown root:root $PASSWORD_FILE

Enter fullscreen mode Exit fullscreen mode
  1. **Password Generation Function: **This function generates a random 12-character password using openssl.
# Function to generate a random password
generate_password() {
    openssl rand -base64 12
}

Enter fullscreen mode Exit fullscreen mode

4.** User Creation and Group Assignment:** This is the core of the script:

  • It reads each line of the input file, expecting a format of user;groups.
  • It checks if the user or group already exists. If not, it generates a password, creates the user,creates the group sets the password, and logs these actions.
  • It sets the home directory permissions to 700 to ensure only the user has access.
  • It assigns the user to the specified groups, logging each action.
# Read the input file line by line
while IFS=';' read -r user groups; do
    # Check if the user already exists
    if id "$user" &>/dev/null; then
        echo "User $user already exists." | sudo tee -a $LOG_FILE
    else
        # Generate a random password
        password=$(generate_password)

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

        # Log the creation and password
        echo "User $user created with home directory." | sudo tee -a $LOG_FILE
        echo "$user:$password" | sudo tee -a $PASSWORD_FILE

        # Set the permissions and ownership of the home directory
        sudo chmod 700 /home/$user
        sudo chown $user:$user /home/$user

        # Assign groups to the user
        IFS=',' read -r -a group_array <<< "$groups"
        for group in "${group_array[@]}"; do
            # Check if the group exists
            if ! getent group "$group" &>/dev/null; then
                # Create the group if it does not exist
                sudo groupadd "$group"
                echo "Group $group created." | sudo tee -a $LOG_FILE
            fi
            sudo usermod -aG "$group" "$user"
            echo "User $user added to group $group." | sudo tee -a $LOG_FILE
        done
    fi
done < "$INPUT_FILE"

echo "User creation, group assignment, and logging completed." | sudo tee -a $LOG_FILE
Enter fullscreen mode Exit fullscreen mode

5. Running the Script: To run the script, save it as create_users.sh, make it executable, and execute it with the input file as an argument:

chmod +x create_users.sh
sudo ./create_users.sh <input_file>

Enter fullscreen mode Exit fullscreen mode

Conclusion
This script will not only create users and assign them to groups but also create any missing groups. This ensures that all specified groups are present, and users are correctly added to them. This is my stage one project of the HNG internship program. To know more about HNG internship programs please do check the links below
https://hng.tech/internship, https://hng.tech/premium

πŸ’– πŸ’ͺ πŸ™… 🚩
gbenga700
Gbenga Ojo-Samuel

Posted on July 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related