Skip to main content

Command Palette

Search for a command to run...

Comprehensive Guide: Linux User(s) Creation using Bash Script

Published
5 min readView as Markdown

Introduction

In the dynamic field of DevOps, automating routine tasks like user management is pivotal for efficiency and consistency. This guide explores a Bash script designed to create Linux users, assign them to specified groups, log actions, and securely store passwords. Whether you're a seasoned DevOps engineer, a budding system administrator, or an enthusiastic learner like myself enrolled in the HNG internship, mastering this script can significantly enhance your automation skills and contribute to robust system management practices.

Script Overview

Shebang and Description

#!/bin/bash

The script starts with #!/bin/bashEnsuring compatibility with the Bash shell environment is essential for executing Bash scripts effectively.

Checking for Arguments

if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <user_file>"
    exit 1
fi

To maintain script integrity, it checks whether the correct number of arguments (in this case, the user input file) is provided during execution. This ensures clarity and prevents unexpected errors.

File Existence Check

USER_FILE="$1"

if [ ! -f "$USER_FILE" ]; then
    echo "Error: File $USER_FILE does not exist."
    exit 1
fi

The script verifies the existence of the specified user input file ($1). If the file is not found, it promptly notifies the user with an error message, ensuring smooth execution by handling potential file-related issues upfront.

Variable Assignments

LOG_FILE="/var/log/user_management.log"
PASSWORD_DIR="/var/secure"
PASSWORD_FILE="$PASSWORD_DIR/user_passwords.csv"

To streamline file management and ensure clarity within the script, critical paths and filenames are assigned to variables. This practice not only enhances script readability but also facilitates future modifications and scalability.

Log File Creation

touch $LOG_FILE

To maintain a systematic record of script actions and facilitate troubleshooting, the script ensures the existence of a log file (user_management.log). The touch command updates the file's access and modification timestamps or creates it if it doesn't already exist.

Password Directory and File Setup

if [ ! -d "$PASSWORD_DIR" ]; then
    mkdir -p "$PASSWORD_DIR"
    chmod 700 "$PASSWORD_DIR"
fi

if [ ! -f "$PASSWORD_FILE" ]; then
    echo "username,password" >> $PASSWORD_FILE
fi
chmod 600 $PASSWORD_FILE

Recognizing the importance of security in managing sensitive data like passwords, the script meticulously sets up the password directory (/var/secure). If the directory doesn't exist, it creates it with restricted permissions (700), ensuring only authorized access. Additionally, it manages the password file (user_passwords.csv) by initializing it with a header and setting appropriate permissions (600) to safeguard sensitive information.

Logging Function

log_action() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}

To provide visibility into script execution and facilitate comprehensive audit trails, a dedicated log_action function is defined. This function captures timestamped actions and appends them to the log file (user_management.log), ensuring clarity and accountability in script operations.

Reading and Processing the Input File

while IFS=';' read -r username groups; do

    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

Operating in dynamic environments often necessitates handling varied input formats effectively. The script utilizes IFS=';' to process each line of the user input file, separating username and groups data fields. This technique ensures consistency and accuracy in data parsing, preparing the script for diverse operational scenarios.

User and Group Creation

    if id -u "$username" >/dev/null 2>&1; then
        log_action "User $username already exists."
        continue
    fi

    if ! getent group "$username" >/dev/null 2>&1; then
        groupadd "$username"
    fi

    useradd -m -g "$username" -s /bin/bash "$username"

    chmod 700 /home/"$username"
    chown "$username:$username" /home/"$username"

    password=$(openssl rand -base64 12)

    echo "$username:$password" | chpasswd

    echo "$username,$password" >> $PASSWORD_FILE

Effective user management forms the backbone of system administration tasks. The script checks for existing users and, if necessary, creates corresponding user groups to maintain organizational structure and operational efficiency. It ensures home directory permissions (700) are correctly set, assign ownership, generate secure passwords using OpenSSL, and manage password storage securely in the designated file (user_passwords.csv).

Additional Groups

    if [ -n "$groups" ]; then
        IFS=',' read -r -a group_array <<< "$groups"
        for group in "${group_array[@]}"; do
            group=$(echo "$group" | xargs)
            if ! getent group "$group" >/dev/null 2>&1; then
                groupadd "$group"
            fi
            usermod -aG "$group" "$username"
        done
    fi

    log_action "User $username created with groups: $username, $groups"
done < $USER_FILE

In dynamic environments, user roles often extend beyond primary assignments. The script accommodates additional user groups specified in the input file ($groups). It iterates through each group, ensuring their existence and adding the user to these groups using usermod -aG. This flexibility ensures comprehensive user role management, adapting to diverse organizational needs seamlessly.

Logging Completion

log_action "User creation process completed."

Upon successfully creating users and assigning roles, the script concludes by logging the completion of the user creation process. This final step provides a comprehensive overview of script operations, ensuring transparency and enabling effective troubleshooting if needed.

Running the Script

To run the script, follow these steps:

  1. Clone the Script: Ensure you have the Bash script (create_users.sh) available on your Linux machine.

  2. Prepare User Input File: Create a text file (user_list.txt) containing usernames and their associated groups in the format username;groups. For example:

     user1;group1,group2
     user2;group3
     user3;
    
  3. Execute the Script: Open your terminal and navigate to the directory containing create_users.sh.

     chmod +x create_users.sh
     ./create_users.sh user_list.txt
    

    Replace user_list.txt with the path to your prepared user input file.

  4. Verify Execution: Monitor the terminal for script output. Check /var/log/user_management.log for detailed logs of the script's actions.

  5. Password Storage: Passwords are securely stored in /var/secure/user_passwords.csv. Only the file owner has read access to maintain confidentiality.

Conclusion

This comprehensive guide demonstrates the critical role of automation in DevOps environments, emphasizing efficient user management practices through a Bash script. By understanding and customizing this script, DevOps engineers, system administrators, and aspiring interns like myself can enhance operational efficiency, strengthen security protocols, and maintain meticulous audit trails. As I continue my journey in the HNG internship program, mastering these foundational skills is essential for progressing to more advanced stages and contributing effectively to real-world projects.

For more information about the HNG Internship program and its benefits, visit HNG Internship and HNG Premium.