Automating User and Group Management with a Bash Script

Gen-Z Full stack Engineer. Interested in Backend, Flutter, Physics and Web3.
Introduction
Effective management of user accounts and groups is essential for any organization, particularly during the onboarding process for new hires. Automating these processes as a SysOps engineer can help you save a ton of time and effort while maintaining consistency and security. This post will guide you through the process of creating a bash script that creates users and groups automatically, configures home directories, creates strong passwords, and records all activity.
Why This Script is Necessary
Manually creating user accounts and groups is a tedious and error-prone task. Imagine having to set up home directories with the proper rights, establish dozens of accounts, make sure each user is allocated to the correct groups, create random passwords, and log every action. This procedure can quickly become too much to handle.
By automating these tasks, you:
Save Time: Automation speeds up the process of user creation, reducing the time taken to onboard new employees.
Reduce Errors: Manual entry is prone to mistakes. Automation ensures consistency and accuracy.
Improve Security: Automatically generated passwords are more secure than those manually created. Secure storage and proper permissions add another layer of security.
Maintain Logs: Automated logging provides a clear audit trail, which is essential for compliance and troubleshooting.
The Solution
To address this problem, I've created a bash script called create_users.sh. This script reads a text file containing usernames and groups, creates the necessary accounts, assigns users to groups, sets up home directories, generates random passwords, and logs all actions. Let's dive into the script and see how it works.
The Script
The source code can be found in its repository at https://gitlab.com/theadeyemiolayinka-hng-11/devops/user-and-group-management-script/-/blob/main/create_users.sh?ref_type=heads
Code Summary
1. Setting Up Log and Secure Directories
The script begins by defining the paths for the log file and the secure password storage:
LOG_FILE="/var/log/user_management.log"
SECURE_DIR="/var/secure"
PASSWORD_FILE="$SECURE_DIR/user_passwords.csv"
It ensures that the secure directory exists and sets the proper permissions to prevent unauthorized access:
mkdir -p $SECURE_DIR
chmod 700 $SECURE_DIR
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
2. User Creation Function
The create_user function is responsible for creating a user, assigning them to groups, setting up their home directory, generating a random password, and logging these actions:
create_user() {
local username=$1
local groups=$2
# Check if user already exists
if id "$username" &>/dev/null; then
echo "User $username already exists" | tee -a $LOG_FILE
else
# Create user with home directory and personal group
useradd -m -s /bin/bash -g $username $username
echo "User $username created" | tee -a $LOG_FILE
# Create specified groups if they don't exist and add user to them
IFS=',' read -r -a group_array <<< "$groups"
for group in "${group_array[@]}"; do
if ! getent group "$group" > /dev/null 2>&1; then
groupadd "$group"
echo "Group $group created" | tee -a $LOG_FILE
fi
usermod -aG "$group" "$username"
done
echo "User $username added to groups $groups" | tee -a $LOG_FILE
# Set permissions for home directory
chmod 700 /home/$username
chown $username:$username /home/$username
echo "Home directory for $username set up with appropriate permissions" | tee -a $LOG_FILE
# Generate random password
password=$(openssl rand -base64 12)
echo $username,$password >> $PASSWORD_FILE
echo "Password for $username generated and stored securely" | tee -a $LOG_FILE
fi
}
Here's a breakdown of what the function does:
Checks if User Already Exists: It first checks if the user already exists using the
idcommand. If the user exists, it logs this information and skips the creation process.Creates User and Personal Group: If the user doesn't exist, it creates the user with a home directory and a personal group using the
useraddcommand.Creates and Assign Groups: It creates the specified groups if they don't already exist and assigns the user to these groups using the
usermodcommand.Sets Home Directory Permissions: It sets the permissions for the home directory to ensure only the user has access.
Generate Random Password: It generates a random password using
openssl rand -base64 12and stores it securely in the password file. This promotes security as passwords are randomly generated.
3. Reading the Input File
The script expects a text file as an argument, where each line contains a username and a list of groups separated by a semicolon. It reads each line, removes any whitespace, creates a personal group for the user, and calls the create_user function:
# Ensure the text file is provided as an argument
if [ $# -ne 1 ]; then
echo "Usage: $0 <name-of-text-file>"
exit 1
fi
# Read the text file and process each line
while IFS=';' read -r username groups; do
# Remove whitespace
username=$(echo "$username" | xargs)
groups=$(echo "$groups" | xargs)
# Check if the personal group already exists before creating it
if ! getent group "$username" > /dev/null 2>&1; then
groupadd $username
echo "Group $username created" | tee -a $LOG_FILE
fi
# Create user and assign groups
create_user $username "$groups"
done < $1
4. Logging and Error Handling
The script logs all actions performed to /var/log/user_management.log for auditing purposes. It also handles errors gracefully, ensuring existing users are not duplicated and providing informative messages for each step.
5. Example Input FIle
light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
Why This Solution is Effective
Automation: Automating the user and group management process saves time and reduces the risk of human error.
Security: Using randomly generated passwords and storing them securely, the script ensures that user credentials are protected.
Consistency: The script enforces consistent user and group creation practices, ensuring all users are set up with the correct permissions and groups.
Logging: Comprehensive logging provides an audit trail, which is essential for security and troubleshooting.
Conclusion
This bash script simplifies the process of managing users and groups in a Linux environment. By automating these tasks, you can ensure consistency, security, and efficiency in your SysOps duties. Feel free to customize the script to suit your specific needs and organizational policies.
This blog post is part of a submission to a task on the HNG 11 Internship program.
For more information about the HNG Internship, check out the HNG Internship and HNG Premium websites.
Happy automating!



