Step-by-Step Guide to Creating a Linux User with a Bash Script

Step-by-Step Guide to Creating a Linux User with a Bash Script

Introduction

Automating user management tasks is crucial for efficient system administration in today's DevOps landscape. This article provides a comprehensive guide to creating a bash script that automates the process of user creation, group assignment, password generation, logging, and secure password storage.
Prerequisites

Before starting, ensure you have:

  • A Linux environment (Ubuntu recommended)

  • Basic knowledge of bash scripting and Linux system administration

Task Overview

The task involves creating a bash script (create_users.sh) that:

  • Reads user and group information from a text file.

  • Creates users with personal groups and additional specified groups.

  • Sets up home directories with appropriate permissions.

  • Generates random passwords for users.

  • Logs all actions to /var/log/user_management.log.

  • Stores generated passwords securely in /var/secure/user_passwords.csv.

Step-by-Step Guide

1. Setting Up Your Environment
  1. Open a Terminal: Access your Linux environment where you will create and run the script.

  2. Create the Script: Use a text editor like nano or vim to create create_users.sh.

     nano create_users.sh
    
  3. Writing the Bash Script

#!/bin/bash

# Function to generate random password
generate_password() {
    # Generate a random 12-character alphanumeric password
    pw=$(openssl rand -base64 12)
    echo "${pw//[^a-zA-Z0-9]/}"  # Remove special characters
}

# Main script starts here

# Check if the script is run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root" >&2
    exit 1
fi

# Check if the argument 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.csv"

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

# Read input file line by line
while IFS=';' read -r username groups; do
    # Trim whitespace
    username=$(echo "$username" | tr -d '[:space:]')
    groups=$(echo "$groups" | tr -d '[:space:]')

    # Check if user already exists
    if id "$username" &>/dev/null; then
        echo "User $username already exists. Skipping."
        echo "$(date) - User $username already exists. Skipping." >> "$log_file"
        continue
    fi

    # Create user and personal group
    groupadd "$username"
    useradd -m -s /bin/bash -g "$username" "$username"

    # Add additional groups
    IFS=',' read -ra group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        groupadd "$group"
        usermod -aG "$group" "$username"
    done

    # Generate and set password
    password=$(generate_password)
    echo "$username:$password" | chpasswd

    # Log user creation and password generation
    echo "User $username created with password: $password"
    echo "$(date) - User $username created with password: $password" >> "$log_file"

    # Store username and password in secure file
    echo "$username,$password" >> "$password_file"

done < "$input_file"

echo "User creation process complete. Please review $log_file for details."
  1. Explanation of the Script

Memory updated

To create a technical article detailing the step-by-step guide on how to execute the DevOps task of creating a Linux user creation bash script, here’s a structured approach you can follow:


Title: Step-by-Step Guide to Creating a Linux User Creation Bash Script

Introduction

In today's DevOps landscape, automating user management tasks is crucial for efficient system administration. This article provides a comprehensive guide to creating a bash script that automates the process of user creation, group assignment, password generation, logging, and secure password storage.

Prerequisites

Before starting, ensure you have:

  • A Linux environment (Ubuntu recommended)

  • Basic knowledge of bash scripting and Linux system administration

Task Overview

The task involves creating a bash script (create_users.sh) that:

  • Reads user and group information from a text file.

  • Creates users with personal groups and additional specified groups.

  • Sets up home directories with appropriate permissions.

  • Generates random passwords for users.

  • Logs all actions to /var/log/user_management.log.

  • Stores generated passwords securely in /var/secure/user_passwords.csv.

Step-by-Step Guide

1. Setting Up Your Environment
  1. Open a Terminal: Access your Linux environment where you will create and run the script.

  2. Create the Script: Use a text editor like nano or vim to create create_users.sh.

     bashCopy codenano create_users.sh
    
2. Writing the Bash Script

Below is the detailed script:

bashCopy code#!/bin/bash

# Function to generate random password
generate_password() {
    # Generate a random 12-character alphanumeric password
    pw=$(openssl rand -base64 12)
    echo "${pw//[^a-zA-Z0-9]/}"  # Remove special characters
}

# Main script starts here

# Check if script is run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root" >&2
    exit 1
fi

# Check if argument 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.csv"

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

# Read input file line by line
while IFS=';' read -r username groups; do
    # Trim whitespace
    username=$(echo "$username" | tr -d '[:space:]')
    groups=$(echo "$groups" | tr -d '[:space:]')

    # Check if user already exists
    if id "$username" &>/dev/null; then
        echo "User $username already exists. Skipping."
        echo "$(date) - User $username already exists. Skipping." >> "$log_file"
        continue
    fi

    # Create user and personal group
    groupadd "$username"
    useradd -m -s /bin/bash -g "$username" "$username"

    # Add additional groups
    IFS=',' read -ra group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        groupadd "$group"
        usermod -aG "$group" "$username"
    done

    # Generate and set password
    password=$(generate_password)
    echo "$username:$password" | chpasswd

    # Log user creation and password generation
    echo "User $username created with password: $password"
    echo "$(date) - User $username created with password: $password" >> "$log_file"

    # Store username and password in secure file
    echo "$username,$password" >> "$password_file"

done < "$input_file"

echo "User creation process complete. Please review $log_file for details."
3. Explanation of the Script
  • Initialization: Checks if the script is run as root and verifies input file existence.

  • User Creation: Iterates through each line of the input file, creating users with their groups and additional specified groups.

  • Password Generation: Uses openssl to generate random passwords securely.

  • Logging: Logs all actions to /var/log/user_management.log.

  • Password Storage: Stores usernames and passwords securely in /var/secure/user_passwords.csv.

  1. Executing the Script

Make the Script Executable:

chmod +x create_users.sh

Run the Script:

sudo ./create_users.sh input_file.txt
  1. Verification
    • Check Logs: Verify user creation and password generation details in /var/log/user_management.log.

    • Password Security: Ensure /var/secure/user_passwords.csv is accessible only to the file owner (chmod 600).

Conclusion

This guide has demonstrated how to automate user creation and management tasks using a bash script on Linux. By following these steps, you can streamline user provisioning, enhance security, and maintain detailed logs for auditing purposes.

For further details on system administration and automation tasks, consider exploring the HNG Internship program, which provides valuable insights into modern DevOps practices