DEV Community

Udoh Deborah
Udoh Deborah

Posted on

Automating User Creation: A Streamlined Approach

Managing user accounts can be a time-consuming task, especially when dealing with frequent onboarding. on my stage one task with https://hng.tech/internship, I took a deep dive into automating User Creation. This guide introduces a Bash script, create_users.sh, that automates user creation and management based on a text file.

  • The Script's Purpose

create_users.sh aims to automate user account creation on Linux systems. It reads a user data file containing usernames and associated groups. The script then performs a series of actions to ensure each user is set up correctly with appropriate permissions and group memberships.

#!/bin/bash

# Log file location
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Check if the input file is provided
if [ -z "$1" ]; then
  echo "Error: No file was provided"
  echo "Usage: $0 <name-of-text-file>"
  exit 1
fi

# Create log and password files
mkdir -p /var/secure
touch $LOGFILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

generate_random_password() {
  local length=${1:-10} # Default length is 10 if no argument is provided
  LC_ALL=C tr -dc 'A-Za-z0-9!?%+=' < /dev/urandom | head -c $length
}

# Function to create a user
create_user() {
  local username=$1
  local groups=$2

  if getent passwd "$username" > /dev/null; then
    echo "User $username already exists" | tee -a $LOGFILE
  else
    useradd -m $username
    echo "Created user $username" | tee -a $LOGFILE
  fi

  # Add user to specified groups
  groups_array=($(echo $groups | tr "," "\n"))

  for group in "${groups_array[@]}"; do
    if ! getent group "$group" >/dev/null; then
      groupadd "$group"
      echo "Created group $group" | tee -a $LOGFILE
    fi
    usermod -aG "$group" "$username"
    echo "Added user $username to group $group" | tee -a $LOGFILE
  done

  # Set up home directory permissions
  chmod 700 /home/$username
  chown $username:$username /home/$username
  echo "Set up home directory for user $username" | tee -a $LOGFILE

  # Generate a random password
  password=$(generate_random_password 12)
  echo "$username:$password" | chpasswd
  echo "$username,$password" >> $PASSWORD_FILE
  echo "Set password for user $username" | tee -a $LOGFILE
}

# Read the input file and create users
while IFS=';' read -r username groups; do
  create_user "$username" "$groups"
done < "$1"

echo "User creation process completed." | tee -a $LOGFILE
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Breakdown

    • Creating the Script:
    • Use touch create_users.sh to create the script file.
    • Make the script executable with chmod +x create_users.sh.
  1. **Input File Check:

  • The script checks if you provided a user data file containing user and group information. This prevents errors and ensures proper usage.
  • Create a sample data file (e.g., user_data.txt) using sudo nano user_data.txt.
  1. Key Script Components:
  • The script defines essential variables like LOG_FILE and PASSWORD_FILE to manage file paths throughout the script. This improves readability and simplifies maintenance.
  1. Security Measures:
  • Prioritizing security, the script creates necessary directories (if missing) and initializes a password file (/var/secure/user_passwords.csv) with strict permissions (chmod 600). This restricts access to sensitive password information.
  1. Modular Functions:
  • The script defines functions for better organization:
    • generate_password(): Uses OpenSSL to generate strong, random passwords.
    • log_message(): Logs detailed actions with timestamps to a log file for troubleshooting and auditing.
  1. Processing the Input File:
  • The script reads each line in the user data file, parses usernames and groups, and performs actions for each user:
    • Checks for existing users to avoid duplicates.
    • Creates the user with their primary group and a secure home directory (if the user doesn't exist).
    • Generates a random password stored securely in the password file.
    • Creates additional groups (if needed) and adds the user to those groups.
  1. Script Completion:
  • Upon successful user creation, the script logs a message and prompts you to review the log file for details.

Important Considerations

  • Password Security: The script leverages OpenSSL for strong passwords and stores them securely with restricted permissions.
  • Detailed Logging: Logging aids in troubleshooting and provides an audit trail for accountability.
  • Error Handling: The script anticipates potential issues (missing files, existing users) and handles them gracefully to avoid disruptions.
  • Modular Functions: Functions promote code reuse and maintainability.
  • Group Management: The script dynamically manages groups, ensuring proper user access control.

Real-World Application

This script can be valuable in various scenarios, such as:

  • Efficient User Provisioning: During project expansions, the script can streamline user creation, reducing manual effort.
  • Enhanced Security: Secure password generation and storage practices improve overall system security.

*Learn more about the HNG community on https://hng.tech/premium

Top comments (0)