In this article, I will recount the process I followed to create a Bash script for automating Linux user management tasks. These tasks include adding new users, assigning them to groups, setting up home directories, generating random passwords, and logging all actions. I performed this on a Linux system, specifically on an Amazon EC2 instance running Amazon Linux or Ubuntu.
Prerequisites
Before diving into the script, I ensured I had the following:
Access to a Linux system: I used an Amazon EC2 instance.
A list of users and their respective groups: This was stored in a text file, formatted as
user;groups
.Basic knowledge of SSH and SCP: For transferring files and connecting to the EC2 instance.
Step-by-Step Process
1. Creating the User List File
First, I created a file named user_list.txt
containing the usernames and groups:
light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
2. Writing the Bash Script
Next, I created a file named create_
users.sh
and added the following script:
#!/bin/bash
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
USER_LIST=$1
# Create /var/secure directory if it does not exist
if [ ! -d /var/secure ]; then
sudo mkdir -p /var/secure
sudo chmod 700 /var/secure
fi
# Clear the log file and password file if they exist
: > $LOG_FILE
: > $PASSWORD_FILE
generate_password() {
openssl rand -base64 12
}
# Process each line in the user list file
while IFS=';' read -r username groups; do
# Remove leading and trailing whitespaces from username and groups
username=$(echo "$username" | xargs)
groups=$(echo "$groups" | xargs)
echo "Processing user: $username" | tee -a $LOG_FILE
# Create the personal group for the user
if ! getent group "$username" > /dev/null 2>&1; then
sudo groupadd "$username"
echo "Group $username created" | tee -a $LOG_FILE
else
echo "Group $username already exists" | tee -a $LOG_FILE
fi
# Initialize an array to hold the additional groups
group_array=()
for group in $(echo "$groups" | tr ',' ' '); do
group=$(echo "$group" | xargs) # Remove any extra whitespace
# Check if the group exists
if getent group "$group" > /dev/null 2>&1; then
group_array+=("$group")
else
echo "Invalid group name: $group" | tee -a $LOG_FILE
fi
done
# Join the group array into a comma-separated string
additional_groups=$(IFS=','; echo "${group_array[*]}")
# Create the user
if ! id -u "$username" > /dev/null 2>&1; then
sudo useradd -m -g "$username" -G "$additional_groups" "$username" &>/dev/null
if [[ $? -eq 0 ]]; then
echo "User $username created and added to groups: $additional_groups" | tee -a $LOG_FILE
# Generate a password for the user
password=$(generate_password)
echo "$username:$password" | sudo chpasswd
if [[ $? -eq 0 ]]; then
echo "Password for $username set" | tee -a $LOG_FILE
# Store the password securely (avoid echoing to terminal)
echo "$username,$password" >> $PASSWORD_FILE
else
echo "Failed to set password for user $username" | tee -a $LOG_FILE
fi
# Set permissions on the home directory
sudo chown "$username:$username" "/home/$username"
sudo chmod 700 "/home/$username"
echo "Home directory permissions set for $username" | tee -a $LOG_FILE
else
echo "Failed to create user $username" | tee -a $LOG_FILE
fi
else
echo "User $username already exists" | tee -a $LOG_FILE
fi
done < "$USER_LIST"
echo "User creation process completed. Logs can be found at $LOG_FILE."
3. Transferring Files to the EC2 Instance
I then transferred the script and the user list file to my EC2 instance using SCP:
scp -i C:\path\to\your\key.pem create_users.sh user_list.txt ec2-user@ec2-18-117-167-150.us-east-2.compute.amazonaws.com:/home/ec2-user/scripts/
4. Setting Executable Permissions
I SSH'd into my EC2 instance:
ssh -i /path/to/your/key.pem ec2-user@ec2-18-117-167-150.us-east-2.compute.amazonaws.com
I navigated to the directory where I transferred the files:
cd /home/ec2-user/scripts
And set executable permissions on the script:
chmod +x create_users.sh
5. Running the Script
I ran the script with the user list file as an argument:
sudo ./create_users.sh user_list.txt
6. Verifying the Results
Finally, I checked the log file to see the actions performed by the script:
cat /var/log/user_management.log
I also verified the passwords stored securely:
sudo cat /var/secure/user_passwords.txt
Explanation of the Script
Directory and File Setup
Directory Creation: The script created the
/var/secure
directory if it did not exist, ensuring it had the correct permissions.Log and Password Files: The script cleared the log and password files at the start to ensure fresh logs and password storage.
User and Group Management
Personal Group Creation: Each user got a personal group with the same name.
Group Validation: The script checked if each specified group existed before attempting to add the user to it.
User Creation: Users were created with home directories, personal groups, and additional groups if specified.
Password Generation and Logging
Password Generation: A secure random password was generated using
openssl
.Password Setting: The password was set for the user, and both the username and password were logged securely.
Home Directory Permissions: Proper ownership and permissions were set for the user's home directory.
Troubleshooting
Invalid Group Names
When the script reported invalid group names, I verified if those groups existed:
getent group www-data
getent group sudo
User Already Exists
If a user already existed, the script logged it and skipped the creation process. I ensured the user list was up-to-date and did not contain existing users.
This Bash script automates the user management process on a Linux system, ensuring consistent and secure handling of user accounts. By following the steps I outlined, you can efficiently manage user accounts and maintain logs for auditing purposes.
This article was created as part of my submission for the HNG Internship program. To learn more about the program and its opportunities, please visit HNG Internship, HNG Hire, or HNG Premium.