Creating and Managing Users and Groups on Linux with Bash Scripts: An Efficient Guide 🚀🐧

RMAG news

Welcome to Linux user management! In a growing organization, manually managing user accounts and groups can quickly become tedious and error-prone. To streamline this process and maintain security and productivity, automation is key. 🛠️💪

With a Bash script, you can automate the repetitive tasks of creating and managing users and groups, ensuring consistency and efficiency while saving countless hours and reducing the risk of errors.

In this article, we’ll show you how to create a script to automate the user and group creation process—a common task for any SysOps engineer. Let’s dive in and simplify your workflow! 🌟

Prerequisites

Linux or Ubuntu running on either VM (Virtual box), Docker, AWS Ec2 instance.
Basic knowledge of Linux commands and Bash scripting.
Root privileges to execute the script.
Basic understanding of shell scripting and user management in Linux

Step 1: Create user file
Create a .txt file where your users will be listed and the groups they should be added to. A simple and easy to read file will be recommended. For this article , a sample file user.txt has been created and will be formatted as user;groups

Example

Adeshile;sudo,dev,www-data
Mayowa;sudo
Kunle;dev,www-data

The first line in the example above Adeshile is the user and groups are sudo, dev, www-data.

Step 2: Create script file
Open your code editor and create a file e.g create_users.sh, this can also be created in your root directory using your terminal by running:

touch create_users.sh

NB: The script file created will handle the logic of the user and group in Step 1

Step 3: Script implementation
First we need to check the administrative priviledge of the script user.

Check if the first argument is passed:

The script begins with a shebang line and a check for root privileges to ensure the necessary permissions for user and group management.

if (( “$UID != 0” ))
then
echo “Error: script requires root privilege”
fi
exit 1

Shebang (#!/bin/bash): Indicates that the script should be run in the Bash shell.
Root Privileges Check: Verifies if the script is executed by the root user. If not, it prints an error and exits.

Then , the script processes input arguments and checks for the presence and type of the file (text/plain) containing user data.

# Save all arguments in an array
ARGS=(“$@”)

# Check whether no arguments are supplied
if [ “$#” -eq 0 ]; then
echo “No arguments supplied”
exit 1
fi

# Define a variable for the file
FILE=${ARGS[0]}

# Check if the file exists
if [ ! -f “$FILE” ]; then
echo “Error: File $FILE does not exist.”
exit 1
fi

# Get the MIME type and check if it is text/plain
file_type=$(file -b –mime-type “$FILE”)
if [[ “$file_type” != “text/plain” ]]; then
echo “Error: required file type is not text/plain”
exit 1
fi

Argument Handling: Captures script arguments and checks if any are provided.
File Existence Check: Verifies if the specified file exists.
MIME Type Check: Ensures the file is a plain text file.

Logging and Data Writing Functions
I used this function below to log all actions by logging all user actions into /var/log/user_management.log

# Logging and writing data
log() {
sudo printf “$*n” >> $log_path
}

# Function to save user data
user_data() {
sudo printf “$1,$2n” >> $3
}

Generate Random Passwords
genpasswd function is used to generate a secure random password of specified length (default 16 characters)for the user.

genpasswd() {
local l=$1
[ “$l” == “” ] && l=16
tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}

Process Each Line in the users.txt file:
The below code block will read each line of users.txt file and get the username and user groups.

# Create user function
create_user() {
username=”$1″
password=$(genpasswd)
if ! id -u “$username” >/dev/null 2>&1; then
sudo useradd -m -s /bin/bash $username
echo “$username:$password” | sudo chpasswd
msg=”User ‘$username’ created with the password ‘$password'”
echo $msg
log $msg
dir=/home/$username/$user_pass
create_file_directory $dir
user_data $username $password $dir
sudo chgrp $username $dir
sudo chmod 640 $dir
fi
}

# Create group function
create_group() {
if ! getent group “$1” >/dev/null; then
sudo groupadd $1
msg=”Group created ‘$1′”
echo $msg
log $msg
fi
}

# Add user to group function
add_user_to_group() {
sudo usermod -aG $2 $1
msg=”‘$1’ added to ‘$2′”
echo $msg
log $msg
}

The code block above contains the following functions:
create_user Function: Creates a user with a home directory and sets the password.
create_group Function: Creates a group if it doesn’t already exist.
add_user_to_group Function: Adds a user to a specified group.

The user and password is created and then the details are then stored in the user directory using the below path:
user home directory]/var/secure/user_passwords.txt

The user data reads file and creates users and groups accordingly.

# Read the FILE
while IFS= read -r line || [ -n “$line” ]; do
username=$(printf “%s” “$line” | cut -d ‘;’ -f 1)
echo “—– Process started for: ‘$username’ —–“
create_user $username
usergroups=$(printf “%s” “$line” | cut -d ‘;’ -f 2)
for group in ${usergroups//,/ } ; do
create_group $group
add_user_to_group $username $group
done
echo “—– Process Done with ‘$username’ —–“
done < $FILE

Step 4: Run script file

It’s time to test our script to ensure that our code is working.

Run the .txt file by using the command below on your terminal.

bash create_users.sh users.txt

The below result should be displayed:

root@32cb601ed360:~# bash create_users.sh users.txt
File and path created: /var/log/user_management.log
—– Process started for: ‘Adeshile’ —–
‘Adeshile’ added to ‘sudo’
‘Adeshile’ added to ‘dev’
‘Adeshile’ added to ‘www-data’
—– Process Done with ‘Adeshile’ —–
—– Process started for: ‘Mayowa’ —–
‘Mayowa’ added to ‘sudo’
—– Process Done with ‘Mayowa’ —–
—– Process started for: ‘Kunle’ —–
‘Kunle’ added to ‘dev’
‘Kunle’ added to ‘www-data’
—– Process Done with ‘Kunle’ —–

User ‘Adeshile’ created with the password ‘mx8XszQDRbm1Rqp5’
‘Adeshile’ added to ‘sudo’
‘Adeshile’ added to ‘dev’
‘Adeshile’ added to ‘www-data’
User ‘Mayowa’ created with the password ‘ucBhqg4j0B69byEn’
‘Mayowa’ added to ‘sudo’
User ‘Kunle’ created with the password ‘YSM99v3iRQb6dFwh’
‘Kunle’ added to ‘dev’
‘Kunle’ added to ‘www-data’
‘Adeshile’ added to ‘sudo’
‘Adeshile’ added to ‘dev’
‘Adeshile’ added to ‘www-data

To see all groups created run:

sudo cat /etc/group

To see all users and groups they belong run:

sudo cat /etc/passwd

My full code implementation can be found on Github: Creating and Managing Users

HNG Internships
For more information about the HNG Internship, visit [HNG Internship (https://hng.tech/internship) and if you want to hire world class freelancers and developers , check: HNG Hire.

Thanks for reading through please do ensure to leave feedback so as to better serve my reader 😊

Conclusion
This Bash script automates the process of creating and managing users and groups on a Linux system, making it easier to maintain consistency and security across your user base. By following this guide, you can efficiently manage user accounts and group memberships with minimal manual effort.