Automating User and Group Management with Bash Scripting
Simplifying User and Group Management with create_users.sh
In today's dynamic business environments, efficient management of user accounts and group memberships is critical for maintaining security and operational efficiency. To address this challenge effectively, I developed create_users.sh
, a powerful bash script designed to automate the creation and management of users and groups on Linux systems. This article explores the capabilities of create_users.sh
, explains its implementation details, and provides comprehensive instructions for deployment and usage.
Understanding create_users.sh
create_users.sh
streamlines user and group management by:
Reading a structured text file to create users with their respective home directories and personal groups.
Assigning users to additional groups based on predefined roles or project requirements.
Generating strong, random passwords for each user and securely storing them.
Logging all script activities for auditing and troubleshooting purposes.
Key Features and Benefits
Automated User Setup: The script reads an input file formatted as username;groups
, where each line specifies a user and their associated groups. It checks if users already exist, creates new ones with their respective home directories, and ensures each user has a personal group for enhanced security.
Flexible Group Management: Beyond personal groups, users can be assigned to multiple additional groups as specified in the input file. This flexibility facilitates collaboration across different projects or functional teams while maintaining robust access controls.
Secure Password Handling: Passwords generated by the script are strong and securely stored in /var/secure/user_passwords.csv
. Strict file permissions (chmod 600
) ensure that only authorized personnel can access these passwords, enhancing overall system security.
Comprehensive Logging and Error Handling: All actions performed by create_users.sh
, including user creations, group assignments, and password generation, are logged in /var/log/user_management.log
. Error handling mechanisms prevent issues such as duplicate user creation or invalid input file formats, ensuring reliable script execution.
Detailed Script Explanation
#!/bin/bash
# Check if script is executed with root privileges
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
# Check if input file is provided as argument
if [ $# -ne 1 ]; then
echo "This is how you run this script: $0 <input-file>"
exit 1
fi
INPUT_FILE=$1
# Check if input file exists and is readable
if [ ! -f "$INPUT_FILE" ] || [ ! -r "$INPUT_FILE" ]; then
echo "Error: $INPUT_FILE does not exist or is not readable"
exit 1
fi
# Log file path
LOG_FILE="/var/log/user_management.log"
# Function to generate random password
generate_password() {
# Generate a 12-character random alphanumeric password
openssl rand -base64 16 | tr -dc 'a-zA-Z0-9' | head -c 12
}
# Read input file and create users
while IFS=';' read -r username groups; do
# Trim whitespace from username and groups
username=$(echo "$username" | tr -d '[:space:]')
groups=$(echo "$groups" | tr -d '[:space:]')
# Check if user already exists
if id "$username" &>/dev/null; then
echo "$(date) - User $username already exists, skipping." >> "$LOG_FILE"
continue
fi
# Create user with home directory
useradd -m -s /bin/bash "$username"
# Create personal group for the user if not exists
if ! grep -q "^$username:" /etc/group; then
groupadd "$username"
fi
# Add user to their personal group
usermod -aG "$username" "$username"
# Add user to additional 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 random password for the user
password=$(generate_password)
# Set password for the user
echo "$username:$password" | chpasswd
# Log user creation details
echo "$(date) - Created user $username with groups: $groups" >> "$LOG_FILE"
# Store password securely
# Check if /var/secure directory exists
if [ ! -d /var/secure ]; then
mkdir -p /var/secure
fi
# Append username and password to the file
echo "$username,$password" >> /var/secure/user_passwords.csv
done < "$INPUT_FILE"
# Secure permissions for password file
chmod 600 /var/secure/user_passwords.csv
# Completion message
echo "$(date) - User creation process completed." >> "$LOG_FILE"
Script Breakdown
Root Privilege Check:
- Verifies if the script is executed with root privileges (
$EUID -ne 0
), necessary for system-level user and group management.
- Verifies if the script is executed with root privileges (
Input File Check:
- Ensures that an input file is provided when running the script (
$# -ne 1
). If not, it displays usage instructions and exits.
- Ensures that an input file is provided when running the script (
File Existence and Readability Check:
- Verifies if the specified input file exists and is readable (
[ ! -f "$INPUT_FILE" ] || [ ! -r "$INPUT_FILE" ]
). If not, it logs an error and exits.
- Verifies if the specified input file exists and is readable (
Log File Initialization:
- Defines the path (
/var/log/user_management.log
) where all script activities, including user creations and password assignments, are logged for auditing and troubleshooting.
- Defines the path (
Password Generation Function:
generate_password()
function uses OpenSSL to generate a 12-character random alphanumeric password for each user.
User Creation Loop:
Reads each line of the input file (
users.txt
), where each line containsusername;groups
.Trims any leading or trailing whitespace from
username
andgroups
variables.
Check User Existence:
- Uses
id "$username"
to check if the user already exists. If so, it logs a message and skips to the next user in the input file.
- Uses
Create User and Home Directory:
useradd -m -s /bin/bash "$username"
creates a new user (-m
creates a home directory for the user).
Create Personal Group:
- Checks if the personal group (
$username
) exists; if not, creates it usinggroupadd
.
- Checks if the personal group (
Add User to Personal Group:
usermod -aG "$username" "$username"
adds the user to their personal group for enhanced security.
Add User to Additional Groups:
- Splits
groups
by commas (IFS=',' read -ra user_groups <<< "$groups"
) and adds the user to each specified additional group usingusermod -aG
.
- Splits
Generate and Set Password:
- Generates a random password and securely assigns it to the user using
echo "$username:$password" | chpasswd
.
- Generates a random password and securely assigns it to the user using
Logging:
- Logs detailed information about each user creation, including
username
andgroups
, to/var/log/user_management.log
for auditing purposes.
- Logs detailed information about each user creation, including
Secure Password Storage:
Checks if the directory
/var/secure
exists; if not, creates it to store passwords securely.Appends
username,password
pairs to/var/secure/user_passwords.csv
, ensuring strict access control withchmod 600
to protect sensitive information.
Completion Message:
- Logs a completion message to
/var/log/user_management.log
indicating the successful completion of the user creation process.
- Logs a completion message to
Getting Started with create_users.sh
To implement create_users.sh
in your environment and automate user and group management effectively, follow these steps:
Download the Script:
- Clone or download
create_users.sh
from the GitHub repository to your Linux server or workstation.
- Clone or download
Adjust Permissions:
- Ensure
create_users.sh
is executable (chmod +x create_users.sh
) and located in a convenient directory.
- Ensure
Prepare Input File:
- Create a text file (
users.txt
) formatted with each line specifyingusername;groups
, wheregroups
are comma-separated.
- Create a text file (
Run the Script:
Execute the script with root privileges (
sudo
) and provide the prepared input file as an argument:sudo ./create_users.sh users.txt
Review Logs:
- Check
/var/log/user_management.log
to review detailed logs of all script activities, ensuring successful user creations and group assignments.
- Check
Manage Passwords Securely:
- Access and manage passwords stored in
/var/secure/user_passwords.csv
cautiously, restricting access to authorized personnel only.
- Access and manage passwords stored in
Explore Opportunities with HNG Internship
For those interested in enhancing their skills in system administration and automation, explore the HNG Internship program and HNG Premium. These platforms provide valuable resources and industry insights to support your professional development in the tech field.
Conclusion
By leveraging create_users.sh
, organizations can streamline user and group management processes, reduce manual efforts, and enhance overall security and compliance
Subscribe to my newsletter
Read articles from Benjamin Adeyele directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by