My HNG Experience Stage One: User Management and Automation With Bash script

lois_oseodion_9055bdf056d

Lois Oseodion

Posted on July 5, 2024

My HNG Experience Stage One: User Management and Automation With Bash script

The HNG Internship has me on a thrilling ride! My first project is to create a Bash script to automate user management on a Linux server. This project showcases scripting's power and highlights the skills I'm gaining at HNG. Get ready to see how this script simplifies user and group management!

Prerequisites and Requirements
Prerequisites:

Access to a Linux environment (e.g., Ubuntu)
Basic understanding of how to run scripts and manage files in a Linux terminal
Permissions to create users, groups, and files
Requirements:
Input File Format: The script will read a text file where each line is formatted as {username; groups}.

Example:

kelvin; admin,dev
Hannah; dev,tester
Gift; admin,tester
Enter fullscreen mode Exit fullscreen mode

Script Actions:
Create users (kelvin, Hannah, Gift) and their personal groups (admin, dev, tester).
Place users in the designated additional groups (admin, dev, tester).
Create home directories for each user with the correct permissions.
Create random passwords for each user.
Record all actions in /var/log/user_management.log.
Save passwords securely in /var/secure/user_passwords.txt.
Gracefully manage errors, such as users or groups that already exist.

Step-by-Step Implementation
Step 1:
Script Initialization and Setup
Set up the initial environment for the script, including defining file locations and creating necessary directories.
Define File Locations: Initializes paths for logging and password storage.
Create Directories: Ensures necessary directories exist.
Set File Permissions: Create and set permissions for the log and password files.

#!/bin/bash

# Define log and password file locations
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

# Create Directories
mkdir -p /var/log
mkdir -p /var/secure

# Create and set permissions for the log file
touch $LOG_FILE
chmod 644 $LOG_FILE

# Create and set permissions for the password file
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

Enter fullscreen mode Exit fullscreen mode

Step 2:
Logging Function Creation
Create a function to log actions performed by the script with timestamps.

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

Enter fullscreen mode Exit fullscreen mode

Step 3:
Argument Checking
Verify that the script is provided with the correct number of arguments.

# Check if a correct number of arguments is provided.
if [ $# -ne 1 ]; then
  log_action "Usage: $0 <user-list-file>. Exiting."
  exit 1
fi

USER_LIST_FILE=$1

# Check if user list file exists
if [ ! -f $USER_LIST_FILE ]; then
  log_action "File $USER_LIST_FILE does not exist! Exiting."
  exit 1
fi

Enter fullscreen mode Exit fullscreen mode

Step 4:
Reading and Processing User List
Read each line from the user list file, extracting usernames and associated groups.

# Process each line in the user list file
while IFS=';' read -r username groups; do
  username=$(echo $username | xargs)
  groups=$(echo $groups | xargs)

  # Further actions based on extracted data will be performed in subsequent steps.
done < $USER_LIST_FILE

Enter fullscreen mode Exit fullscreen mode

Step 5:
User Existence Checking and Creation
Verify if each user already exists; if not, create the user.

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

# Create the user if they do not exist
useradd -m $username
if [ $? -eq 0 ]; then
  log_action "User $username created successfully."
else
  log_action "Failed to create user $username."
  continue
fi

Enter fullscreen mode Exit fullscreen mode

Step 6:
Group Handling
Create the necessary groups for each user and assign them appropriately.

# Assign user to specified additional groups
IFS=',' read -ra USER_GROUPS <<< "$groups"
for group in "${USER_GROUPS[@]}"; do
  group=$(echo $group | xargs)
  if ! getent group $group >/dev/null; then
    groupadd $group
    if [ $? -eq 0 ]; then
      log_action "Group $group created successfully."
    else
      log_action "Failed to create group $group."
      continue
    fi
  fi
  usermod -aG $group $username
  log_action "User $username added to group $group."
done

Enter fullscreen mode Exit fullscreen mode

Step 7:
Home Directory Setup
Ensure each user has a home directory set up with appropriate permissions.

# Set up home directory permissions
chmod 755 /home/$username
chown $username:$username /home/$username
log_action "Home directory permissions set for user $username."

Enter fullscreen mode Exit fullscreen mode

Step 8:
Password Generation and Storage
Generate a secure password for each user and store it securely.

# Generate and store passwords securely
password=$(date +%s | sha256sum | base64 | head -c 12 ; echo)
echo "$username,$password" >> $PASSWORD_FILE
log_action "Password for user $username set successfully."

Enter fullscreen mode Exit fullscreen mode

Step 9:
Script Completion and Finalization
Conclude the script execution, logging the completion of all actions.

# Final log entry
log_action "Script execution completed."

Enter fullscreen mode Exit fullscreen mode

Putting It All Together
Here's the complete script:

#!/bin/bash

# Step 1: Define File Locations
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

# Step 2: Create Directories
mkdir -p /var/log
mkdir -p /var/secure

# Step 3: Set File Permissions
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
touch $LOG_FILE
chmod 644 $LOG_FILE

# Step 4: Define Logging Function
log_action() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') : $1" >> $LOG_FILE
}

# Step 5: Argument Checking
if [ $# -ne 1 ]; then
  log_action "Usage: $0 <user-list-file>. Exiting."
  exit 1
fi

USER_LIST_FILE=$1

if [ ! -f $USER_LIST_FILE ]; then
  log_action "File $USER_LIST_FILE does not exist! Exiting."
  exit 1
fi

# Step 6: Reading and Processing User List
while IFS=';' read -r username groups; do
  username=$(echo $username | xargs)
  groups=$(echo $groups | xargs)

  # Step 7: User Existence Checking and Creation
  if id -u $username >/dev/null 2>&1; then
    log_action "User $username already exists. Skipping."
    continue
  fi

  useradd -m $username
  if [ $? -eq 0 ]; then
    log_action "User $username created successfully."
  else
    log_action "Failed to create user $username."
    continue
  fi

  # Step 8: Group Handling
  IFS=',' read -ra USER_GROUPS <<< "$groups"
  for group in "${USER_GROUPS[@]}"; do
    group=$(echo $group | xargs)
    if ! getent group $group >/dev/null; then
      groupadd $group
      if [ $? -eq 0 ]; then
        log_action "Group $group created successfully."
      else
        log_action "Failed to create group $group."
        continue
      fi
    fi
    usermod -aG $group $username
    log_action "User $username added to group $group."
  done

  # Step 9: Home Directory Setup
  chmod 755 /home/$username
  chown $username:$username /home/$username
  log_action "Home directory permissions set for user $username."

  # Step 10: Password Generation and Storage
  password=$(date +%s | sha256sum | base64 | head -c 12 ; echo)
  echo "$username,$password" >> $PASSWORD_FILE
  log_action "Password for user $username set successfully."

done < $USER_LIST_FILE

# Step 11: Script Completion and Finalization
log_action "Script execution completed."

Enter fullscreen mode Exit fullscreen mode

Trying It Out
Save the file as create_user.sh.
Upload it to a GitHub repository.
Clone the repository to a Linux server.
Run the script with the user list file as an argument.

The HNG project is more than just an internship; it is a transformative experience that equips participants with the skills, knowledge, and confidence needed to thrive in the fast-paced tech industry. Honestly, I am enjoying it. Thanks for taking the time to read this far. Please kindly like and leave a comment. Thank you!

💖 💪 🙅 🚩
lois_oseodion_9055bdf056d
Lois Oseodion

Posted on July 5, 2024

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

Sign up to receive the latest update from our blog.

Related