Automating Linux User Creation with Bash Scripts
Introduction
Managing users on a Linux system can be a repetitive and error-prone task, especially when dealing with a large number of users. Automating this process with a bash script can save time and reduce the risk of mistakes. In this article, we’ll walk through a bash script that reads a text file containing usernames and group names, creates users and groups, sets up home directories, generates random passwords, logs actions, and stores passwords securely.
Refer to this github repository to get a hold of the script and this was inspired by hng intership
Script Breakdown:
- Input Validation and Initialization
#!/bin/bash
# Check if the script is executed with a file argument
if [ $# -eq 0 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
input_file=$1
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"
Purpose: Validates that the script is called with an input file argument and initializes variables.
Function:
- Uses
#!/bin/bash
to indicate this script should be executed using Bash. - Checks if the script is provided with an argument (
$#
checks the number of arguments). - Prints a usage message and exits if no argument is provided.
- Sets
input_file
,log_file
, andpassword_file
variables based on the provided argument and predetermined file paths.
2. Password Generation Function
# Function to generate a random password
generate_password() {
openssl rand -base64 12 | tr -d '/+=' | cut -c1-12
}
Purpose: Defines a function to generate a random password.
Function:
- Uses
openssl rand -base64 12
to generate a random 12-character base64-encoded string. tr -d '/+='
removes characters that may not be suitable for passwords.cut -c1-12
ensures the password length is exactly 12 characters.
3. Main Processing Loop
# Loop through each line in the input file
while IFS=';' read -r username groups; do
# Remove leading/trailing whitespace
username=$(echo "$username" | tr -d '[:space:]')
groups=$(echo "$groups" | tr -d '[:space:]')
# Check if the user already exists
if id "$username" &>/dev/null; then
echo "User $username already exists. Skipping."
echo "$(date) - User $username already exists. Skipping." >> "$log_file"
continue
fi
# Create the user
useradd -m -s /bin/bash "$username"
# Create groups if they don't exist and add the user to groups
IFS=',' read -ra user_groups <<< "$groups"
for group in "${user_groups[@]}"; do
if ! grep -q "^$group:" /etc/group; then
groupadd "$group"
fi
usermod -aG "$group" "$username"
done
# Generate a password
password=$(generate_password)
# Set the password for the user
echo "$username:$password" | chpasswd
# Log actions
echo "$(date) - Created user $username with groups $groups." >> "$log_file"
# Store passwords securely
echo "$username,$password" >> "$password_file"
# Ensure home directory permissions
chown -R "$username:$username" "/home/$username"
chmod 700 "/home/$username"
done < "$input_file"
Purpose: Processes each line in the input file (users.txt
) to create users, assign them to groups, generate passwords, log actions, and store passwords securely.
Function:
- Uses
while IFS=';' read -r username groups; do
to read each line, splitting by;
intousername
andgroups
. - Removes any leading/trailing whitespace from
username
andgroups
. - Checks if the user already exists using
id "$username" &>/dev/null
. - Creates the user with
useradd -m -s /bin/bash "$username"
. - Creates specified groups if they don’t exist and adds the user to each group.
- Generates a password using the
generate_password
function. - Sets the generated password for the user using
echo "$username:$password" | chpasswd
. - Logs the creation action with timestamp to
$log_file
. - Stores the username and password securely in
$password_file
. - Ensures correct permissions on the user’s home directory (
/home/$username
)
4. Script Completion
echo "User creation process complete."
Purpose: Indicates the completion of the script’s execution.
Function: Prints a message to the terminal indicating that the user creation process has finished.
Summary
This script automates the creation of user accounts on a Linux system based on input provided in a text file (users.txt
). It handles user and group creation, generates secure passwords, logs actions to /var/log/user_management.log
, and stores passwords securely in /var/secure/user_passwords.txt
. The script ensures correct permissions on user home directories and provides feedback throughout its execution. Adjustments and enhancements can be made based on specific requirements or additional functionality needed.