This article explains a Bash script designed to streamline the process of creating users, assigning groups, and managing passwords securely. Whether you are an intern at HNG or an experienced System Administrator, understanding this script can be a valuable addition to your toolkit.
Script Overview
This script automates the creation of user accounts and their respective groups from a specified input file. It also logs activities and securely stores generated passwords.
#!/bin/bash
# Log file
LOG_FILE="/var/log/user_management.log"
# Secure passwords file
PASSWORD_FILE="/var/secure/user_passwords.csv"
# Create log and password files if they don't exist
sudo mkdir -p /var/log /var/secure
sudo touch $LOG_FILE $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
# Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $LOG_FILE > /dev/null
}
# Check if input file is provided
if [ -z "$1" ]; then
echo "Usage: sudo ./create_users.sh <input_file>"
exit 1
fi
# Read usernames and groups from the provided text file
while IFS=';' read -r username groups; do
# Remove any leading/trailing whitespace
username=$(echo "$username" | xargs)
groups=$(echo "$groups" | xargs)
# Skip empty lines
[ -z "$username" ] && continue
# Create user and personal group
sudo useradd "$username" -m -U
log_message "User $username created"
# Create additional groups if they don't exist and add user to groups
IFS=',' read -ra group_array <<< "$groups"
for group in "${group_array[@]}"; do
sudo groupadd -f "$group"
sudo usermod -aG "$group" "$username"
log_message "User $username added to group $group"
done
# Set permissions and ownership for home directory
sudo chown "$username:$username" "/home/$username"
# Generate a random password
password=$(openssl rand -base64 12)
echo "$username:$password" | sudo chpasswd
# Store passwords securely in /var/secure/user_passwords.csv
echo "$username,$password" | sudo tee -a $PASSWORD_FILE > /dev/null
done < "$1"
sudo chmod 600 $PASSWORD_FILE
log_message "User creation script completed."
Let's dive into each section of the script to understand its functionality.
Setting Up Log and Password Files
#!/bin/bash
# Log file
LOG_FILE="/var/log/user_management.log"
# Secure passwords file
PASSWORD_FILE="/var/secure/user_passwords.csv"
# Create log and password files if they don't exist
sudo mkdir -p /var/log /var/secure
sudo touch $LOG_FILE $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
Explanation:
Log and Password File Variables: The script defines the log file (
LOG_FILE
) and the password file (PASSWORD_FILE
).Directory and File Creation: It ensures that the necessary directories and files exist, creating them if they don't.
sudo mkdir -p
creates directories, whilesudo touch
creates files.Permission Setting:
sudo chmod 600
sets strict permissions for the password file to ensure only the root user can read and write to it, enhancing security.
Logging Function
# Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $LOG_FILE > /dev/null
}
Explanation:
- Logging Function: The
log_message
function appends a timestamped message to the log file. This helps in tracking script activities and debugging issues.
Input File Check
# Check if input file is provided
if [ -z "$1" ]; then
echo "Usage: sudo ./create_users.sh <input_file>"
exit 1
fi
Explanation:
- Input Validation: The script checks if an input file is provided. If not, it displays a usage message and exits. This ensures the script runs with the necessary data.
Processing the Input File
# Read usernames and groups from the provided text file
while IFS=';' read -r username groups; do
# Remove any leading/trailing whitespace
username=$(echo "$username" | xargs)
groups=$(echo "$groups" | xargs)
# Skip empty lines
[ -z "$username" ] && continue
Explanation:
Reading Input File: The
while
loop reads each line of the input file, splitting it intousername
andgroups
based on the semicolon (;
) delimiter.Trimming Whitespace: The
xargs
command removes any leading or trailing whitespace from theusername
andgroups
variables.Skipping Empty Lines: The script skips any empty lines to avoid errors.
User and Group Management
# Create user and personal group
sudo useradd "$username" -m -U
log_message "User $username created"
# Create additional groups if they don't exist and add user to groups
IFS=',' read -ra group_array <<< "$groups"
for group in "${group_array[@]}"; do
sudo groupadd -f "$group"
sudo usermod -aG "$group" "$username"
log_message "User $username added to group $group"
done
# Set permissions and ownership for home directory
sudo chown "$username:$username" "/home/$username"
Explanation:
Creating User and Primary Group:
sudo useradd "$username" -m -U
creates a user and their personal group. The-m
flag creates a home directory, and-U
creates a group with the same name as the user.Logging User Creation: The script logs the creation of the user.
Managing Additional Groups: The script reads the additional groups, creates them if they don't exist (
sudo groupadd -f
), and adds the user to these groups (sudo usermod -aG
).Setting Home Directory Permissions:
sudo chown
sets the ownership of the user's home directory to the user and their personal group.
Password Management
# Generate a random password
password=$(openssl rand -base64 12)
echo "$username:$password" | sudo chpasswd
# Store passwords securely in /var/secure/user_passwords.csv
echo "$username,$password" | sudo tee -a $PASSWORD_FILE > /dev/null
done < "$1"
sudo chmod 600 $PASSWORD_FILE
log_message "User creation script completed."
Explanation:
Generating and Setting Passwords: The script generates a random password using
openssl rand -base64 12
and sets it for the user usingsudo chpasswd
.Storing Passwords Securely: The script appends the username and password to the secure password file.
Final Permissions: It sets the file permissions of the password file to ensure security.
Completion Log: The script logs the completion of the user creation process.
Conclusion
This Bash script is a powerful tool for automating user management in Linux. By understanding each component, you can customize and extend its functionality to meet your specific needs. For more insights into automating system administration tasks, consider exploring the HNG Internship program and HNG premium services. These resources provide valuable learning and networking opportunities for aspiring tech professionals.
Understanding and leveraging scripts like this can significantly enhance your productivity and security practices, making you a more effective system administrator.