Automating Linux User Creation with Bash Scripts
Emmanuel Nwanochie
·
2024-07-04
·
3 min read
Originally published on Medium

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, and password_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 ; into username and groups.
- Removes any leading/trailing whitespace from username and groups.
- 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.
More articles
The Layers of a Network Request: nginx stream vs HTTP Proxying
Two backends terminating their own TLS meant I needed end-to-end TLS passthrough, not termination at the proxy — which sent me into the layers of a network request and onto nginx's Layer 4 stream module.
Building CaricatureCam: Real-Time Face Warping in the Browser
How I built a browser-based app that applies real-time facial caricature effects to your webcam at 30+ FPS — entirely on-device, using MediaPipe, React, and a pluggable effects architecture.
Handy Javascript Array Methods
There are really handy array methods in javascript to keep in mind when trying to manipulate data within an array to get your desired output. I would be going…