Automating Linux User Management with Bash Scripts

mubarak_ajibola_96a34686b

Mubarak ajibola

Posted on July 3, 2024

Automating Linux User Management with Bash Scripts

Introduction
Automation is essential for improving operational efficiency and preserving system consistency in today's dynamic IT environments. This article examines a bash script meant to automate Linux system user administration. The script was created as part of the HNG Internship DevOps Stage 1 work and helps with password generation, user creation, group assignments, security logging, and permissions configuration.

Script Overview
To efficiently handle users, the bash script create_users.sh makes use of essential Linux commands and facilities. The program creates random passwords securely using OpenSSL, reads user and group data from an input file (users.txt), processes each entry to create users with their corresponding groups, configures home directories with the necessary permissions, and records all operations to /var/log/user_management.log.It also makes sure that generated passwords are stored securely in /var/secure/user_passwords.csv.

Key Features and Functionality

Input File Processing:

  • The script parses users.txt, where each line specifies a username followed by semicolon-separated groups (e.g., username; group1,group2).

User and Group Management:

  • Checks if each user and their primary group exists. If not, it creates them.
  • Adds users to specified additional groups and creates those groups if they don't exist.

Password Management:

  • Generates strong, random passwords for each user using OpenSSL.
  • Sets the generated password securely and logs the event to provide an audit trail.

Home Directory Setup:

  • Ensures each user has a home directory created with strict permissions (700) and ownership for security.

Logging and Auditing:

  • All operations performed by the script are logged with timestamps in /var/log/user_management.log. This facilitates troubleshooting and auditing of user management activities.

Security Considerations:

  • Passwords are stored securely in /var/secure/user_passwords.csv, with permissions restricted (600) and ownership restricted to root. This ensures only authorized personnel can access password information.

Script Implementation: create_users.sh

1. Script Initialization and Input Handling

#!/bin/bash

# Ensure script is run with root privileges
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

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

INPUT_FILE=$1

# Check if the input file exists
if [ ! -f $INPUT_FILE ]; then
    echo "Input file not found!"
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode

2. File and Directory Setup

# Log file path
LOG_FILE="/var/log/user_management.log"
# Password file path
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Create the secure directory if it doesn't exist
mkdir -p /var/secure
chmod 700 /var/secure

# Create the log file if it doesn't exist and set permissions
touch $LOG_FILE
chmod 600 $LOG_FILE


Enter fullscreen mode Exit fullscreen mode

3. Logging Function

# Function to log messages with timestamps
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}
Enter fullscreen mode Exit fullscreen mode

4. User and Group Management

# Loop through each line in the input file
while IFS=";" read -r username groups; do
    # Remove leading and trailing whitespace
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)

    # Create the user group if it doesn't exist
    if ! getent group "$username" >/dev/null; then
        groupadd "$username"
        log_message "Group $username created."
    else
        log_message "Group $username already exists."
    fi

    # Create the user if it doesn't exist
    if ! id -u "$username" >/dev/null 2>&1; then
        useradd -m -g "$username" -s /bin/bash "$username"
        log_message "User $username created with home directory."
    else
        log_message "User $username already exists."
        continue
    fi

    # Add user to additional groups specified
    IFS=',' read -ra ADDR <<< "$groups"
    for group in "${ADDR[@]}"; do
        group=$(echo $group | xargs)
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
            log_message "Group $group created."
        fi
        usermod -aG "$group" "$username"
        log_message "User $username added to group $group."
    done

    # Generate a random password for the user
    password=$(openssl rand -base64 12)
    echo "$username:$password" | chpasswd
    echo "$username,$password" >> $PASSWORD_FILE  # Store password in CSV format
    log_message "Password for user $username set and stored."

    # Set permissions for the user's home directory
    chmod 700 /home/"$username"
    chown "$username":"$username" /home/"$username"
    log_message "Permissions for /home/$username set to 700 and ownership set to $username:$username."

done < "$INPUT_FILE"
Enter fullscreen mode Exit fullscreen mode

5. Conclusion

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

Create a Sample Input File: users.txt

light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
Enter fullscreen mode Exit fullscreen mode

Execution and Conclusion
To execute the script, run:

chmod +x create_users.sh
Enter fullscreen mode Exit fullscreen mode

Run the script with root privileges:

sudo ./create_users.sh users.txt
Enter fullscreen mode Exit fullscreen mode

This article offers a thorough analysis of the create_users.sh script, demonstrating its powerful automation capabilities for Linux system user management chores. Organizations may improve security through standard operating procedures, expedite user provisioning, and keep thorough audit logs of all user management operations by putting this script into effect.

For more information on the HNG Internship and opportunities in tech, visit HNG Internship and HNG Hire.

💖 💪 🙅 🚩
mubarak_ajibola_96a34686b
Mubarak ajibola

Posted on July 3, 2024

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

Sign up to receive the latest update from our blog.

Related