Automating user and group creation using bash script

Bridget
CodeX
Published in
5 min readJul 1, 2024

Imagine you are SysOps engineer at a tech company and you are always creating user accounts, setting up home directories ,assigning groups and generating passwords for new developers joining the team. This seems like a repetitive and boring task. Then you start thinking 🤔 ,how you can I automate this task? This is where the power of bash script comes in.

A bash script automates repetitive tasks, ensuring consistency, accuracy and efficiency in task management. It also allows one to save countless hours and reduce the risk of errors

In this article, we will discuss how to create a script that automates user and group creation process which is a common task of a SysOps engineer.

We will start by creating a script file called ,`create_users.sh`.

nano create_users.sh

Functions of the script

  1. Create users and groups as specified
  2. Set up home directories with appropriate permissions and ownership
  3. Generate random passwords for the users
  4. Log all actions to /var/log/user_management.log.
  5. Store the generated passwords securely in /var/secure/user_passwords.txt

Prerequisites

  • Basic knowledge of Linux commands and Bash scripting.
  • An understanding of root or sudo access to execute user and group management commands.
  • A text file containing the user and group information in the specified format.

However, do not be limited by this prerequisites if you do not have them because you will learn as you do the task.

Now that we understand what the script is supposed to do and the prerequisites to complete this task, let’s add logic to our script.

Step 1: Check root privileges

Since user and group management commands require administrative access, the script verifies if it’s run as root.

# Check if running as root
if [[ $UID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi

Step 2: Read the user file

The script checks if the user file is provided as an argument and uses it when it is executed

#Check if the file with users and their corresponding groups exists
if ["$#" -ne 1]; then
echo "Use: $0 <user_file>"
exit 1
fi

Step 3: Initialize password and log file

We will initialize the values of the log and password file. If the files do not exist, we need to create them. For the password file, we need to set appropriate permissions where only the user can read and write it.

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

# Create the log and password files if they do not exist
touch $LOG_FILE
mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

Step 4: Create a user function

The purpose of the function is :

  • Checking if the user already exists.
  • Creating a personal group for each user.
  • Creating the user and adding them to specified groups.
  • Generating a random password.
  • Setting the user’s password.
  • Logging the action and storing the password securely.
# Create a user function
create_user() {

#declare the variables with local scope and assign them a value
local user = $1
local groups = $2
local password

# Check if user already exists
if id "$user" &>/dev/null; then
#Creates the user and logs the process
echo "User $user already exists " | tee -a $LOG_FILE
return 1
fi

#Create users personal group
#Use the groupadd command used in unix OS to create a new group
#The new group has the same name as the user
groupadd "$user"


#Use the useradd command to create a new user
#The -m flag creates a home directory for the user if it does not exist
#The -g flag assigns the user to the group
#The -G flag assigns the user to additional groups
#The 2>>$LOG_FILE redirects the standard error to the log file
useradd -m -g "$user" -G "$groups" "$user" 2>>$LOG_FILE

#Check if the user group was created successfully
if [ $? -ne 0 ]; then
echo "Failed to create group $user" | tee -a $LOG_FILE
return 1
fi

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

#Set users password
#Outputs the user and password to the chpasswd command
#The chpasswd command reads eads a list of user name and password pairs from standard input
#and updates the system password file
echo "$user:$password" | chpasswd
if [ $? -ne 0 ]; then
echo "Failed to set password for user $user" | tee -a $LOG_FILE
return 1
fi

#Store the password securely
#The password is stored in the /var/secure/user_passwords.txt file
#The file is created if it does not exist
#The file permissions are set to 600
echo "$user:$password" >> $PASSWORD_FILE

#Log the user creation
echo "Created user $user with groups $groups" | tee -a $LOG_FILE

}

Step 5: Process the user file

The script reads each line from the user file created then it processes the usernames and groups of the users. Finally it calls the create_user function

#Read the user file line by line
#The IFS variable is used to set the field separator to ';'
#The read command reads the user and groups from the file
while IFS=';' read -r user groups; do
#The xargs command is used to remove leading and trailing whitespaces
user=$(echo $user | xargs)
groups=$(echo $groups | xargs)

#The create_user function is called with the user and groups as arguments
create user "user" "groups"
done < "$USER_FILE"

#Log the completion of the user creation process
echo "User creation process completed." | tee -a $LOG_FILE

Running the script

  1. Create users file

Add your users and their groups in the format user;groups. Save and close the file.

nano users.txt

You can try out the sample I have provided as your users.txt file

harry; sudo,dev,www-data
pow; sudo
dangle; dev,www-data
sency; www-data

2. Make the file and the script executable

chmod +x users.txt

chmod +x create_script.sh

3. Run the script

sudo ./create_script.sh users.txt

Automating the user and group creation process helps in:

  • Time Efficiency: Saves time by automating repetitive tasks.
  • Consistency: Ensures all users are created with the correct groups and permissions.
  • Security: Generates random passwords and logs actions for auditing.

Learn about HNG internship

This article is task 2 in the devops track of HNG Internship. HNG internship is a great platform to horn your skills in various fields in technology. To learn more about HNG checkout thei website https://hng.tech/internship.

If you’re looking to hire talented developers, visit HNG Hire for more information.

By following this guide, you can streamline the user management process in your organization, ensuring that new developers are onboarded quickly and efficiently.

Happy scripting!

--

--