Linux User Creation- Bash Scripting

lucy_76er

Lucy Alfred Joshua

Posted on July 7, 2024

Linux User Creation- Bash Scripting

In today's DevOps environments, automating routine system administration tasks is necessary for efficiency and consistency. One common task is the creation and management of user accounts on Linux systems. This article structure adheres to the technical requirements specified in the HNG Internship stage one task.

HNG Task

Your company has employed many new developers. As a SysOps engineer, write a bash script called create_users.sh that reads a text file containing the employee’s usernames and group names, where each line is formatted as user;groups.

Script Development

The Bash script is designed to automate the creation of users based on input from a text file. This script addresses specific requirements such as creating users with appropriate groups, setting up home directories, generating secure passwords, and logging all actions for auditing purposes. Passwords are to be stored securely in /var/secure/user_passwords.txt and all actions logged to /var/log/user_management.log.

1. Setup and Initialization
The script begins by ensuring that the necessary directories and files are in place:

#!/bin/bash

# Ensure log and password files are created and secured
mkdir -p /var/log /var/secure
touch /var/log/user_management.log
touch /var/secure/user_passwords.txt
chmod 600 /var/secure/user_passwords.txt
Enter fullscreen mode Exit fullscreen mode

These commands create /var/log and /var/secure directories if they do not exist. It also initializes user_management.log and user_passwords.txt with appropriate permissions for logging actions and storing passwords securely.

2. Logging Functionality
The script uses a function log_action() to log each action performed during user creation:

# Function to log actions with timestamp
log_action() {
    echo "$(date) - $1" >> "/var/log/user_management.log"
}
Enter fullscreen mode Exit fullscreen mode

This function appends a timestamped message to user_management.log for each significant action, providing a detailed record of user management activities.

3. User Creation Logic
The core of the script involves the create_user() function, which handles user creation based on input parameters:

# Function to create user and manage groups
create_user() {
    local username="$1"
    local groups="$2"
    local password

    # Check if user already exists
    if id "$username" &>/dev/null; then
        log_action "User $username already exists. Skipping."
        return
    fi

    # Create user's primary group
    groupadd "$username"
    log_action "Group $username created."

    # Create additional groups if they don't exist
    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"
            log_action "Group $group created."
        fi
    done

    # Add user to groups
    useradd -m -s /bin/bash -g "$username" "$username"
    if [ $? -eq 0 ]; then
        log_action "User $username created with primary group: $username"
    else
        log_action "Failed to create user $username."
        return
    fi

    for group in "${group_array[@]}"; do
        usermod -aG "$group" "$username"
    done
    log_action "User $username added to groups: ${group_array[*]}"

    # Generate random password
    password=$(</dev/urandom tr -dc A-Za-z0-9 | head -c 12)
    echo "$username:$password" | chpasswd

    # Store password securely
    echo "$username,$password" >> "/var/secure/user_passwords.txt"
    log_action "Password for user $username set and stored securely."

    # Set permissions and ownership
    chmod 700 "/home/$username"
    chown "$username:$username" "/home/$username"
}
Enter fullscreen mode Exit fullscreen mode

This function:

Checks if the user already exists.
Creates the user's primary group.
Checks and creates additional specified groups.
Creates the user account with a home directory and bash shell.
Sets passwords securely.
Logs password creation and user permissions setup.

4. Execution and Input Validation
The script validates input and processes each line from the specified user list file:

# Check for input file argument
if [ $# -ne 1 ]; then
    echo "Usage: $0 <user_list_file>"
    exit 1
fi

filename="$1"

# Verify input file existence
if [ ! -f "$filename" ]; then
    echo "Users list file $filename not found."
    exit 1
fi

# Read user list file and create users
while IFS=';' read -r username groups; do
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs | tr -d ' ')
    groups=$(echo "$groups" | tr ',' ' ')
    create_user "$username" "$groups"
done < "$filename"

echo "User creation process completed."
Enter fullscreen mode Exit fullscreen mode

Bash scripting automates user creation and management on Linux systems, making system administration duties easier and more efficient. By following best practices in security, logging, and error handling, the script (create_users.sh) built in this article illustrates its efficiency in efficiently and safely managing user accounts. This strategy not only increases operational efficiency but also ensures consistency and adherence to organizational security requirements.

References:

Learn more about HNG Internship: HNG Internship Program
Explore further opportunities with HNG: HNG Hire

💖 💪 🙅 🚩
lucy_76er
Lucy Alfred Joshua

Posted on July 7, 2024

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

Sign up to receive the latest update from our blog.

Related