Automating User Creation With Bash Scripting on Linux Systems

Otobong Edoho
4 min readJul 4, 2024

--

Photo by Gabriel Heinzer on Unsplash

Managing users and groups in a Linux environment can be complex and require a lot of processes which can be time-consuming, especially in big organizations that have ever-growing number of users. System admins and SysOps engineers usually face a lot of challenges.

In the fast-paced world of system administration, efficiency is paramount. Automation allows system administrators to perform repetitive tasks quickly and accurately, freeing up valuable time for more strategic initiatives.

Automation in System administration can increase efficiency, consistency, security and so on.

In this article, we will walk you through a Bash script designed to automate the entire process of user creation, group assignment, and home directory setup. This script addresses the challenges mentioned above by:

  • Reading from a text file containing usernames and group names.
  • Creating users and their associated groups.
  • Setting up home directories with appropriate permissions.
  • Generating random, secure passwords for each user.
  • Logging all actions for audit and troubleshooting purposes.

By the end of this article, you will have a comprehensive understanding of how to implement this script in your own environment.

Now, lets dive into the Script.

#!/bin/bash

LOGFILE=/var/log/user_management.log
PASSWORD_FILE=/var/secure/user_passwords.txt

The #!/bin/bash line tells the system to use the Bash interpreter to run the script. The LOGFILE and PASSWORD_FILE variables store the paths to the log file and the password file, respectively.

# A test case to check if the script is run by a root user
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as a root user"
echo "Please log in as a root user to try again"
exit 1
fi

This block ensures that only the root user can run the script, as creating users and groups requires root privileges. If the script is not run as root, it prints an error message and exits , so that other users can mess around with the script. The $EUID returns 0 if the script is run as a root user.

# Checks if there is an argument passed when running the script
# That argument would be our text file containing the employee’s usernames and group names
if [ -z "$1" ]; then
echo "This is how to use it: $0 <userlist-file>"
exit 1
fi

This script is a test case to check if the user entered any arguments at all and exits with a status code of 1 if the user didn’t enter any argument or entered more than 1.

# Here we create the required files for storing the logs and password
# Grant read and write permissions to the owner of the password file
mkdir -p /var/secure
touch $LOGFILE
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

Here, we create the /var/secure directory if it doesn't exist, create the log and password files, and set the permissions on the password file to ensure only the owner can read and write to it.

# This is simple function to log messages and add timestamps
log_message() {
echo "$(date +"%Y-%m-%d %T") : $1" >> $LOGFILE
}

This function appends a timestamped message to the log file, and it takes in one argument before appending it the the log file.

# This is a function to create a user and groups
create_user_and_groups () {
local username=$1
local groups=$2

# checking if user exist if not we create a user
if id "$username" &>/dev/null;
then
log_message "User $username already exists."
else
useradd -m $username
log_message "User $username created."

# Creating a random password for our user
password=$(openssl rand -base64 12)
echo "$username:$password" | chpasswd
echo "$username,$password" >> $PASSWORD_FILE
log_message "Password for $username set."

usermod -aG "$username" "$username"
log_message "User $username added to group $username"
fi
# Process and add the user to other groups
IFS=',' read -ra ADDR <<< "$groups"
for group in "${ADDR[@]}"; do
group=$(echo "$group" | xargs)
if ! getent group "$group" &>/dev/null; then
groupadd "$group"
log_message "Group $group created."
fi
usermod -aG "$group" "$username"
log_message "User $username added to group $group."
done
}

This function does the heavy lifting:

  • It checks if the user already exists. If so, it logs a message and moves on.
  • If the user doesn’t exist, it creates the user, sets a random password, logs the actions, and adds the user to their personal group.
  • It then processes the list of groups, creating any that don’t already exist, and adds the user to each specified group.

Reading the Input File

Finally, we read the input file line by line and call the create_user_and_groups function for each user:

# Read the input file line by line
while IFS=';' read -r username groups;
do
username=$(echo "$username" | xargs)
groups=$(echo "$groups" | xargs)
create_user_and_groups "$username" "$groups"
done < "$1"

echo "User creation process completed. Check $LOGFILE for details."

This loop reads each line of the input file, splits it into username and groups based on the semicolon delimiter, trims any whitespace, and calls the user creation function.

To run this script, save it to a file (e.g., create_users.sh), make it executable, and then run it with the input file as an argument:

chmod +x create_users.sh
sudo ./create_users.sh userlist.txt

Make sure userlist.txt contains lines formatted like :

nathan; sudo,dev,www-data
chris; sudo
joy; dev,www-data

After running the script, you can check /var/log/user_management.log for logs and /var/secure/user_passwords.txt for the generated passwords.

This script is a HNG internship stage 1 task for DevOps track.
To learn more about HNG and what they’ve got to offer visit the following links:

Thank you for reading, and happy automating!

--

--

Otobong Edoho

Otobong Godwin is a passionate DevOps engineer With years of experience 2+ years in Software Development, Otobong is dedicated to sharing knowledge.