Automating User and Group Creation with Bash Scripts

RMAG news

As a SysOps engineer, one of your tasks might involve creating and managing user accounts on a Linux server. To streamline this process, you can automate the creation of users and their associated groups using a bash script. This type of script can be useful in large companies to automate the creation of user accounts and assigning groups, saving time and ensuring consistency, especially when onboarding multiple new employees.

The following guide walks you through a bash script called create_users.sh, which:

Reads a text file containing usernames and groups.

Creates users with home directories and random passwords.

Creates groups and assigns users to them.

Sets up home directories with appropriate permissions.

Logs actions to /var/log/user_management.log.

Stores passwords securely in /var/secure/user_passwords.csv.

Prerequisites:

Ensure you have the necessary permissions and tools:

Before running the script, ensure you have root user privileges because the script requires administrative privileges to create users, groups, and set permissions.
The script also uses the OpenSSL command-line tool to generate secure, random passwords for the new users.
Ensure that OpenSSL is installed on your system.

The Script

create_users.sh script:

#!/bin/bash

# Create log file and secure password file with proper permissions
LOG_FILE=“/var/log/user_management.log”
PASSWORD_FILE=“/var/secure/user_passwords.csv”

# Ensure the script is run as root
if [ $(id -u) -ne 0; then
echo “This script must be run as root.”
exit 1
fi

# Ensure the log file exists
touch $LOG_FILE

# Setup password file
if [ ! -d “/var/secure” ]; then
mkdir /var/secure
fi
if
[ ! -f $PASSWORD_FILE ]; then
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
fi

# Check if the input file is provided
if [ -z $1 ]; then
echo “Usage: bash create_users.sh <name-of-text-file>”
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – ERROR: No input file provided.” >> $LOG_FILE
exit 1
fi

# Read the input file line by line
while IFS=‘;’ read -r username groups; do
# Remove whitespace
username=$(echo $username | xargs)
groups=$(echo $groups | xargs)

# Check if the user already exists
if id $username &>/dev/null; then
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – INFO: User $username already exists.” >> $LOG_FILE
continue
fi

# Create the user with a home directory
useradd -m -s /bin/bash $username
if [ $? -ne 0 ]; then
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – ERROR: Failed to create user $username.” >> $LOG_FILE
continue
fi
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – INFO: User $username created.” >> $LOG_FILE

# Generate a random password for the user
password=$(openssl rand -base64 12)
echo $username:$password | chpasswd

# Save the password to the secure password file
echo $username,$password >> $PASSWORD_FILE
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – INFO: Password for user $username generated and stored.” >> $LOG_FILE

# Create groups for the user
IFS=‘,’ read -ra group_list <<< $groups
for group in ${group_list[@]}; do
group=$(echo $group | xargs)
# Validate group name
if ! grep -qE ‘^[a-z][-a-z0-9]*[$]’ <<< $group; then
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – WARNING: ‘$group‘ is not a valid group name.” >> $LOG_FILE
continue
fi

# Check if the group already exists
if ! getent group $group >/dev/null; then
groupadd $group
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – INFO: Group $group created.” >> $LOG_FILE
fi
# Add the user to the group
usermod -a -G $group $username
done

# Set ownership and permissions for the home directory
chown -R $username:$username “/home/$username
chmod 700 “/home/$username
echo $(date ‘+%Y-%m-%d %H:%M:%S’) – INFO: Home directory for user $username set up with appropriate permissions.” >> $LOG_FILE

done < $1

echo $(date ‘+%Y-%m-%d %H:%M:%S’) – INFO: User creation script completed.” >> $LOG_FILE

exit 0

Creating the Employee List

create a text file (employees.txt) with the following format using any editor: e.g

john; marketing
emma; marketing
alex; sales
lisa; it
mike; it
sara; hr
chris; finance
linda; marketing
james; sales

Running the Script

Upload the script and text file:
Place create_users.sh and employees.txt in a directory on your Ubuntu VM (e.g., /opt/scripts).

Set permissions and execute:

chmod +x /opt/scripts/create_users.sh
sudo /opt/scripts/create_users.sh /opt/scripts/employees.txt

Verifying Execution

After running the script, verify its success by checking:

User creation:

id john

Group assignments:

groups john

Log file:

cat /var/log/user_management.log

Password storage:

cat /var/secure/user_passwords.csv

By following these steps, you can automate user and group management efficiently.

This article is part of a requirement for stage 1 task in HNG11 Internship. For more detailed information, check out the HNG Internship and HNG Hire. These resources provide excellent learning opportunities and support for aspiring SREs and DevOps Engineers.