Managing users and groups on a Linux system can be mudane and task likely to encounter mistakes, especially in environments where users frequently join or leave the system. In this article, I hope to share my idea on creating a Bash script that automates user and group management, ensuring secure password handling and detailed logging.
This is a task i am undertaking as part of my HNG Internship, Hit this link HNG Internship website to join us pursue insightful knowledge, you can aswell reach out to hire skills ready individuals for employment via 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:
sela;developers,admins felix;developers kemuel;admins,users
-
Make the Script Executable:
chmod +x create_user.sh
-
Run the Script:
sudo ./create_user.sh new_user.txt
Conclusion
This Bash script streamlines user management on Linux systems by automating the creation of users with secure passwords, assigning them to the appropriate groups, and logging all actions for audit purposes. This automation helps system administrators save time and minimize errors.
Feel free to customize this script further to suit your specific needs. Happy automating!
Top comments (0)