Automating User Management with a Bash Script
Folayan Donald Michael
Posted on July 4, 2024
Managing users in a Linux environment can be daunting, especially when dealing with multiple users and groups. We can leverage a Bash script to automate user creation, group assignment, and password management to streamline this process. This article walks through creating a robust user management script designed to automate these tasks while ensuring security and logging every step. This script was created for the HNG Internship program and demonstrates practical scripting applications.
Overview of the Script
The script ensures it runs with root privileges, checks for an input file containing user data, and processes each user entry to create users, assign them to groups, and manage their passwords. Here’s a breakdown of each part of the script:
- Checking for Root Privileges: The script starts by checking if it is run as the root user. This is crucial because user management commands require elevated privileges.
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "Error: This script requires root privileges."
echo "Please run with sudo: sudo ./create_users.sh"
exit 1
fi
- Input File Validation: Next, the script checks if an input file is provided. This file should contain user data formatted as username;group1,group2.
if [ $# -eq 0 ]; then
echo "Error: Please provide an input file name as an argument."
exit 1
fi
input_file="$1"
- Logging Function: A logging function is defined to record actions taken by the script. This function writes messages to a log file with a timestamp.
log_message() {
local message="$1"
echo "$(date +'%Y-%m-%d %H:%M:%S') - $message" >> /var/log/user_management.log
}
- Group Addition Function: The group_add function reads the groups from the input and adds the user to each group. It also creates any groups that do not exist.
group_add() {
IFS=',' read -ra group_array <<< "$groups"
for group in "${group_array[@]}"; do
if ! getent group "$group" &>/dev/null; then
groupadd "$group"
log_message "Created group '$group'."
fi
usermod -a -G "$group" "$username"
log_message "User: $username added to group: $group"
done
}
- Directory and File Setup: The script creates necessary directories and files for logging and storing user passwords securely.
mkdir -p /var/secure /var/log
chmod 750 /var/secure /var/log
touch /var/log/user_management.log
chmod 640 /var/log/user_management.log
touch /var/secure/user_passwords.csv
chmod 600 /var/secure/user_passwords.csv
- Processing the Input File: The main part of the script reads each line from the input file, processes user data, and performs the following steps:
- Removes leading/trailing whitespace.
- Checks if the user already exists.
- Creates new users and their home directories.
- Assigns users to specified groups.
- Generates and sets random passwords.
- Logs each action for audit purposes.
while IFS=';' read -r username groups; do
# Remove leading/trailing whitespace
username="${username##* }"
username="${username%% *}"
groups="${groups##* }"
groups="${groups%% *}"
# Skip empty lines
if [ -z "$username" ]; then
continue
fi
# Check if user exists
if id "$username" &>/dev/null; then
log_message "User $username already exists"
group_add
continue
else
# Create user and personal group
useradd -m -s /bin/bash "$username"
log_message "Created user '$username' and group '$username'."
fi
# Create/add user to additional groups
if [ -n "$groups" ]; then
IFS=',' read -ra groupName <<< "$groups"
for group in $(echo "$groups" | tr ',' ' '); do
if ! getent group "$group" &>/dev/null; then
groupadd "$group"
log_message "Created group '$group'."
fi
usermod -a -G "$group" "$username"
log_message "User: $username added to group: $group"
done
fi
# Ensure home directory exists and set permissions
home_dir="/home/$username"
if [ ! -d "$home_dir" ]; then
mkdir "$home_dir"
fi
chown "$username:$username" "$home_dir"
chmod 700 "$home_dir"
# Generate random password, store securely, and update log
password=$(head /dev/urandom | tr -dc A-Za-z0-9 | fold -w 16 | head -n 1)
echo "$username,$password" >> /var/secure/user_passwords.csv
log_message "Generated password for user '$username' and stored securely."
# Set user password
echo "$username:$password" | chpasswd -e /etc/shadow
# Successful user creation
echo "User '$username' created successfully with password stored in /var/secure/user_passwords.csv (READ-ONLY)."
log_message "User '$username' creation completed."
done < "$input_file"
echo "User creation script completed. Refer to /var/log/user_management.log for details."
Security Considerations
The provided script demonstrates password storage in a plain text file. In a production environment, implement secure password management practices like password hashing or integration with a directory service. Additionally, the script should be run with least privilege principles in mind.
Prerequisites
Before using this file, ensure you have the following:
- Linux System: The script is designed for use on Linux systems with Bash as the default shell.
- Bash Shell: Basic understanding of Bash scripting is helpful.
- Essential Utilities: The script utilizes utilities like useradd, groupadd, sed, chmod, openssl, chpasswd, and date. Make sure these are available on your system.
- Root Privileges: The script requires running with root privileges to create user accounts and modify system directories. You can use sudo to run the script with elevated permissions.
- user_data.txt File: This file needs to exist in the same directory as the script and define usernames and groups (one line per user, semicolon separated).
This Bash script provides a comprehensive solution for automating user management in a Linux environment. By ensuring root privileges, validating input, and logging every action, it helps maintain security and auditability. The script can be further extended or customized to meet specific requirements, making it a valuable tool for system administrators. For further exploration of system administration and automation techniques, consider exploring the HNG Internship program (https://hng.tech/internship) or the HNG Premium membership (https://hng.tech/premium) for access to additional resources and professional development opportunities.
Posted on July 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.