Linux Automated User Creation Bash Script

RMAG news

Managing users and groups in a Linux environment can be a time-consuming task, especially in larger organizations. Automating this process with a Bash script can save administrators valuable time and reduce the risk of errors. In this article, we’ll walk through a script designed to automate the creation of users, assignment of groups, and logging of these actions. We will explain the reasoning behind each step to ensure a clear understanding of how the script functions.

This is a task from HNG11 internship program click on the link below to be part of the program:
https://hng.tech/internship

Script Overview
The script performs the following tasks:

**Generates a random password for each user.
Logs actions and errors.
Reads user and group data from an input file.
Creates users and assigns them to specified groups.
Stores user passwords in a secure file.

Step-by-Step Explanation

Setting Absolute Paths for Files**

input_file=”/hng/username.txt” # Update with correct path to username.txt
log_file=”/var/log/user_management.log”
password_file=”/var/secure/user_passwords.txt” # Update with correct secure location

We define the paths for the input file, log file, and password file. The input file contains the usernames and groups, the log file records the actions taken by the script, and the password file stores the generated passwords securely.

Generating Random Passwords

generate_password() {
local password_length=12
local password=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c $password_length)
echo “$password”
}

This function generates a random password of 12 characters using /dev/urandom, a secure random number generator. The password includes uppercase and lowercase letters and digits.

Logging Messages

log_message() {
local log_timestamp=$(date +’%Y-%m-%d %H:%M:%S’)
echo “$log_timestamp – $1” >> “$log_file”
}

The log_message function appends a timestamped message to the log file. This helps track the script’s actions and any issues that arise.

Checking for the Input File

if [ ! -f “$input_file” ]; then
log_message “Error: $input_file not found. Exiting script.”
exit 1
fi

Before proceeding, the script checks if the input file exists. If not, it logs an error message and exits.

Creating the Log File

if [ ! -f “$log_file” ]; then
sudo touch “$log_file”
sudo chmod 644 “$log_file”
log_message “Log file created: $log_file”
fi

If the log file does not exist, the script creates it and sets the appropriate permissions. It then logs that the log file has been created.

Creating the Password File

if [ ! -f “$password_file” ]; then
sudo touch “$password_file”
sudo chmod 600 “$password_file”
sudo chown root:root “$password_file”
log_message “Password file created: $password_file”
fi

Similarly, the script creates the password file if it doesn’t exist and sets strict permissions to ensure its security. It logs the creation of the password file.

Clearing Existing Password File Content

sudo truncate -s 0 “$password_file”
The script clears any existing content in the password file to ensure it only contains current data.

Reading the Input File and Creating Users

while IFS=’;’ read -r username groups; do
username=$(echo “$username” | tr -d ‘[:space:]’)
groups=$(echo “$groups” | tr -d ‘[:space:]’)
password=$(generate_password)

sudo useradd -m -s /bin/bash -G “$groups” “$username” >> “$log_file” 2>&1
echo “$username:$password” | sudo chpasswd >> “$log_file” 2>&1

if [ $? -eq 0 ]; then
log_message “User ‘$username’ created with groups: $groups. Password stored in $password_file.”
echo “$username,$password” | sudo tee -a “$password_file” > /dev/null
sudo chmod 600 “$password_file”
sudo chown root:root “$password_file”
else
log_message “Failed to create user ‘$username’.”
fi
done < “$input_file”

The script reads each line of the input file, which contains usernames and groups separated by a semicolon. It trims any whitespace from the usernames and groups, generates a random password, and attempts to create the user with the specified groups. If the user is successfully created, the password is logged and stored securely. If not, an error message is logged.

Final Log Message

log_message “User creation process completed.”
echo “User creation process completed. Check $log_file for details.”

Once all users have been processed, the script logs a completion message and informs the user to check the log file for details.

Conclusion
By automating user creation and management with this Bash script, system administrators can streamline their workflows, ensure consistency, and reduce the risk of errors. Each step in the script is designed to handle a specific part of the process, from generating passwords to logging actions, ensuring a robust and secure user management solution.

Thank you for reading through this article.
Nb: Do check out https://hng.tech/hire HNG for generational talents in the tech space.