Automating User Creation: A Streamlined Approach
Udoh Deborah
Posted on July 3, 2024
Managing user accounts can be a time-consuming task, especially when dealing with frequent onboarding. on my stage one task with https://hng.tech/internship, I took a deep dive into automating User Creation. This guide introduces a Bash script, create_users.sh
, that automates user creation and management based on a text file.
- The Script's Purpose
create_users.sh
aims to automate user account creation on Linux systems. It reads a user data file containing usernames and associated groups. The script then performs a series of actions to ensure each user is set up correctly with appropriate permissions and group memberships.
#!/bin/bash
# Log file location
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"
# Check if the input file is provided
if [ -z "$1" ]; then
echo "Error: No file was provided"
echo "Usage: $0 <name-of-text-file>"
exit 1
fi
# Create log and password files
mkdir -p /var/secure
touch $LOGFILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
generate_random_password() {
local length=${1:-10} # Default length is 10 if no argument is provided
LC_ALL=C tr -dc 'A-Za-z0-9!?%+=' < /dev/urandom | head -c $length
}
# Function to create a user
create_user() {
local username=$1
local groups=$2
if getent passwd "$username" > /dev/null; then
echo "User $username already exists" | tee -a $LOGFILE
else
useradd -m $username
echo "Created user $username" | tee -a $LOGFILE
fi
# Add user to specified groups
groups_array=($(echo $groups | tr "," "\n"))
for group in "${groups_array[@]}"; do
if ! getent group "$group" >/dev/null; then
groupadd "$group"
echo "Created group $group" | tee -a $LOGFILE
fi
usermod -aG "$group" "$username"
echo "Added user $username to group $group" | tee -a $LOGFILE
done
# Set up home directory permissions
chmod 700 /home/$username
chown $username:$username /home/$username
echo "Set up home directory for user $username" | tee -a $LOGFILE
# Generate a random password
password=$(generate_random_password 12)
echo "$username:$password" | chpasswd
echo "$username,$password" >> $PASSWORD_FILE
echo "Set password for user $username" | tee -a $LOGFILE
}
# Read the input file and create users
while IFS=';' read -r username groups; do
create_user "$username" "$groups"
done < "$1"
echo "User creation process completed." | tee -a $LOGFILE
Step-by-Step Breakdown
-
- Creating the Script:
- Use
touch create_users.sh
to create the script file. - Make the script executable with
chmod +x create_users.sh
.
**Input File Check:
- The script checks if you provided a user data file containing user and group information. This prevents errors and ensures proper usage.
- Create a sample data file (e.g.,
user_data.txt
) usingsudo nano user_data.txt
.
- Key Script Components:
- The script defines essential variables like
LOG_FILE
andPASSWORD_FILE
to manage file paths throughout the script. This improves readability and simplifies maintenance.
- Security Measures:
- Prioritizing security, the script creates necessary directories (if missing) and initializes a password file (
/var/secure/user_passwords.csv
) with strict permissions (chmod 600). This restricts access to sensitive password information.
- Modular Functions:
- The script defines functions for better organization:
-
generate_password()
: Uses OpenSSL to generate strong, random passwords. -
log_message()
: Logs detailed actions with timestamps to a log file for troubleshooting and auditing.
-
- Processing the Input File:
- The script reads each line in the user data file, parses usernames and groups, and performs actions for each user:
- Checks for existing users to avoid duplicates.
- Creates the user with their primary group and a secure home directory (if the user doesn't exist).
- Generates a random password stored securely in the password file.
- Creates additional groups (if needed) and adds the user to those groups.
- Script Completion:
- Upon successful user creation, the script logs a message and prompts you to review the log file for details.
Important Considerations
- Password Security: The script leverages OpenSSL for strong passwords and stores them securely with restricted permissions.
- Detailed Logging: Logging aids in troubleshooting and provides an audit trail for accountability.
- Error Handling: The script anticipates potential issues (missing files, existing users) and handles them gracefully to avoid disruptions.
- Modular Functions: Functions promote code reuse and maintainability.
- Group Management: The script dynamically manages groups, ensuring proper user access control.
Real-World Application
This script can be valuable in various scenarios, such as:
- Efficient User Provisioning: During project expansions, the script can streamline user creation, reducing manual effort.
- Enhanced Security: Secure password generation and storage practices improve overall system security.
*Learn more about the HNG community on https://hng.tech/premium
Posted on July 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.