Automating User and Group Creation with Bash: A Practical Guide

RMAG news

As a SysOps engineer, managing user accounts and groups efficiently is a crucial task. Automation through scripting can significantly streamline this process, ensuring consistency and saving time. In this guide, we’ll walk through a bash script that automates the creation of users and groups based on a provided text file. This script also sets up home directories, generates random passwords, and securely logs all actions.

Script Overview

Our script, create_users.sh, performs the following tasks:

Reads a text file containing usernames and group names.
Creates users and personal groups.
Assigns users to additional groups.
Generates and assigns random passwords.
Logs all actions to /var/log/user_management.log.
Stores passwords securely in /var/secure/user_passwords.txt.

Script Breakdown

Input Validation:

if [ $# -ne 1 ]; then
echo “Usage: $0 <name-of-text-file>”
exit 1
fi

File and Directory Setup:

USER_FILE=$1
LOG_FILE=“/var/log/user_management.log”
PASSWORD_FILE=“/var/secure/user_passwords.txt”

mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
touch $LOG_FILE

Logging Function:

log_action() {
echo $(date ‘+%Y-%m-%d %H:%M:%S’)$1 >> $LOG_FILE
}

Reading and Processing the Input File:

while IFS=‘;’ read -r username groups; do
username=$(echo $username | xargs)
groups=$(echo $groups | xargs)
[ -z $username ] && continue

done < $USER_FILE

User and Group Creation:

if ! getent group $username > /dev/null; then
groupadd $username
log_action “Created group: $username
fi
if
! id -u $username > /dev/null 2>&1; then
useradd -m -g $username -s /bin/bash $username
log_action “Created user: $username with personal group: $username
fi

Assigning Additional Groups:

if [ -n $groups ]; then
IFS=‘,’ read -ra ADDITIONAL_GROUPS <<< $groups
for group in ${ADDITIONAL_GROUPS[@]}; do
group=$(echo $group | xargs)
if ! getent group $group > /dev/null; then
groupadd $group
log_action “Created group: $group
fi
usermod -aG $group $username
log_action “Added user $username to group: $group
done
fi

Generating and Storing Passwords:

PASSWORD=$(openssl rand -base64 12)
echo $username:$PASSWORD | chpasswd
log_action “Set password for user: $username
echo $username,$PASSWORD >> $PASSWORD_FILE

Conclusion

This bash script automates the user management process, ensuring efficiency and security. By integrating this script into your system administration routine, you can handle user accounts and groups with ease.

For more resources and to explore internship opportunities, visit HNG Internship and HNG Hire.