Automating User Management on Linux with Bash

RMAG news

Managing users and groups on a Linux system can be a repetitive and error-prone task, especially in environments where users frequently join or leave the system. In this article, I’ll walk you through creating a Bash script that automates user and group management, ensuring secure password handling and detailed logging.

This task is part of the HNG Internship, a fantastic program that helps interns gain real-world experience. You can learn more about the program at the HNG Internship website or consider hiring some of their talented interns through the HNG Hire page.
The source code can be found on my GitHub

Introduction

User management is a critical task for system administrators. Automating this process not only saves time but also reduces the risk of errors. This script will:

Create users from an input file.
Assign users to specified groups.
Generate secure random passwords.
Log all actions for auditing purposes.

Prerequisites

A Linux system with Bash shell.

sudo privileges to execute administrative commands.

openssl for generating random passwords.

Script Breakdown

Here’s the script in its entirety:

#!/bin/bash
# Check if the input file exists
if [ ! -f $1 ]; then
echo “Error: Input file not found.”
exit 1
fi
# Ensure log and secure directories are initialized once
LOG_FILE=“/var/log/user_management.log”
PASSWORD_FILE=“/var/secure/user_passwords.csv”
# Initialize log file
if [ ! -f $LOG_FILE ]; then
sudo touch $LOG_FILE
sudo chown root:root $LOG_FILE
fi
# Initialize password file
if [ ! -f $PASSWORD_FILE ]; then
sudo mkdir -p /var/secure
sudo touch $PASSWORD_FILE
sudo chown root:root $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
fi
# Redirect stdout and stderr to the log file
exec > >(sudo tee -a $LOG_FILE) 2>&1
# Function to check if user exists
user_exists() {
id $1 &>/dev/null
}
# Function to check if a group exists
group_exists() {
getent group $1 > /dev/null 2>&1
}
# Function to check if a user is in a group
user_in_group() {
id -nG $1 | grep -qw $2
}
# Read each line from the input file
while IFS=‘;’ read -r username groups; do
# Trim whitespace
username=$(echo $username | tr -d ‘[:space:]’)
groups=$(echo $groups | tr -d ‘[:space:]’)
# Check if the user already exists
if user_exists $username; then
echo “User $username already exists.”
else
# Create user
sudo useradd -m $username
# Generate random password
password=$(openssl rand -base64 12)
# Set password for user
echo $username:$password | sudo chpasswd
# Log actions
echo “User $username created. Password: $password
# Store passwords securely
echo $username,$password | sudo tee -a $PASSWORD_FILE
fi
# Ensure the user’s home directory and personal group exist
sudo mkdir -p “/home/$username
sudo chown $username:$username “/home/$username
# Split the groups string into an array
IFS=‘,’ read -ra group_array <<< $groups
# Check each group
for group in ${group_array[@]}; do
if
group_exists $group; then
echo “Group $group exists.”
else
echo “Group $group does not exist. Creating group $group.”
sudo groupadd $group
fi
if
user_in_group $username $group; then
echo “User $username is already in group $group.”
else
echo “Adding user $username to group $group.”
sudo usermod -aG $group $username
fi
done
done
< $1

How It Works

Input File Check: The script starts by checking if the input file exists. If not, it exits with an error message.

Log and Secure File Initialization: It initializes the log and password files, ensuring they have the correct permissions.

Function Definitions: Functions to check user existence, group existence, and user membership in a group are defined.

User and Group Processing: The script reads the input file line by line, processes each username and group, creates users and groups as needed, and assigns users to groups.

Password Handling: Secure random passwords are generated and assigned to new users, and all actions are logged.

Running the Script

Prepare the Input File: Create a file named input_file.txt with the following format:

alice;developers,admins
bob;developers
charlie;admins,users

Make the Script Executable:

chmod +x user_management.sh

Run the Script:

sudo ./user_management.sh input_file.txt

Conclusion

This Bash script simplifies user management on Linux systems, ensuring users are created with secure passwords, assigned to appropriate groups, and all actions are logged for audit purposes. By automating these tasks, system administrators can save time and reduce errors.
Feel free to customize this script further to suit your specific needs. Happy automating!

About the Author

Isaac Obuor is a seasoned DevOps engineer with extensive experience in automating system administration tasks. Follow Isaac Obuor on GitHub for more insightful articles and projects.

These comprehensive README and article drafts should help you document and share your user management script effectively across different platforms.

Start your journey to becoming a world-class developer today!

Please follow and like us:
Pin Share