Automate User and Group Management with Bash: A Comprehensive Guide

RMAG news

Introduction

Managing user accounts and groups is a crucial task for SysOps engineers, especially in an environment with many new developers. This article introduces a Bash script designed to automate these tasks, ensuring efficiency, consistency, and security. The script reads from a text file, creates users and groups as specified, sets up home directories, generates random passwords, logs actions, and stores passwords securely.

Why Automate User and Group Management?

Automation in user management offers several advantages:

Efficiency: Reduces the time spent on repetitive tasks.

Consistency: Ensures uniformity in user setup across the organization.

Security: Automatically generates secure passwords and sets appropriate permissions.

Auditability: Maintains a detailed log of actions for accountability.

The Bash Script: create_users.sh

Here’s a step-by-step breakdown of the script:

#!/bin/bash

# Check if the input file exists
if [ ! -f $1 ]; then
echo “Error: Input file not found.”
exit 1
fi

# Define log and password file locations
LOG_FILE=“/var/log/user_management.log”
PASSWORD_FILE=“/var/secure/user_passwords.csv”

# Initialize log file if it doesn’t exist
if [ ! -f $LOG_FILE ]; then
sudo touch $LOG_FILE
sudo chown root:root $LOG_FILE
sudo chmod 600 $LOG_FILE
fi

# Initialize password file if it doesn’t exist
if [ ! -f $PASSWORD_FILE ]; then
sudo mkdir -p /var/secure
sudo touch $PASSWORD_FILE
sudo chown root:root $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
fi

# Redirect stdout and stderr to the log file
exec > >(sudo tee -a $LOG_FILE) 2>&1

# Function to check if a user exists
user_exists() {
id $1 &>/dev/null
}

# Read each line from the input file
while IFS=‘;’ read -r username groups; do
# Trim whitespace
username=$(echo $username | tr -d ‘[:space:]’)
groups=$(echo $groups | tr -d ‘[:space:]’)

# Check if the user already exists
if user_exists $username; then
echo “User $username already exists.”
continue
fi

# Create user
sudo useradd -m $username

# Create personal group (same as username)
sudo groupadd $username

# Add user to personal group
sudo usermod -aG $username $username

# Create home directory
sudo mkdir -p “/home/$username
sudo chown $username:$username “/home/$username

# Generate random password
password=$(openssl rand -base64 12)

# Set password for user
echo $username:$password | sudo chpasswd

# Log actions
echo “User $username created. Password: $password

# Store passwords securely
echo $username,$password | sudo tee -a $PASSWORD_FILE

# Add user to specified groups
if [ -n $groups ]; then
IFS=‘,’ read -ra group_list <<< $groups
for group in ${group_list[@]}; do
sudo usermod -aG $group $username
echo “Added $username to group $group
done
fi

done < $1

How to Use the Script

Prepare the Input File:
Create a text file where each line follows the format user;groups, with usernames separated from their groups by a semicolon and groups separated by commas.

Example:

light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data

Run the Script:
Execute the script with the input file as an argument:

bash create_users.sh <name-of-text-file>

Verify the Output:

Log File: Check /var/log/user_management.log for a detailed log of actions performed.

Password File: Passwords are securely stored in /var/secure/user_passwords.csv.

Benefits of the Script

Automation: Saves time and reduces human error by automating user creation.

Security: Generates secure passwords and sets appropriate permissions.

Logging: Provides a detailed log for auditing and troubleshooting.

Learn More with HNG Internship

Interested in enhancing your skills and working on real-world projects? Check out the HNG Internship program to learn from industry experts and gain valuable experience. You can also explore opportunities to hire top talent from the HNG community.

Conclusion

Automating user management with a Bash script can significantly improve the efficiency and security of your IT operations. This script provides a robust solution for managing user accounts, ensuring a consistent and secure setup for new developers. By leveraging automation, you can focus on more strategic tasks, confident that new developers are onboarded efficiently and securely.

For the complete script and further details, visit the GitHub repository.

Feel free to leave comments or questions below, and happy automating!

Please follow and like us:
Pin Share