Linux Automated User Creation - Bash Script

jic

Justice Obioha (JIC)

Posted on July 3, 2024

Linux Automated User Creation - Bash Script

Automating User Creation and Management with a Bash Script
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.

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
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
    # Trim leading and trailing whitespace from username and groups
    username=$(echo "$username" | tr -d '[:space:]')
    groups=$(echo "$groups" | tr -d '[:space:]')

    # Generate random password
    password=$(generate_password)

    # Create user with specified groups and set 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"
Enter fullscreen mode Exit fullscreen mode

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."
Enter fullscreen mode Exit fullscreen mode

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

Conclusion and Next Steps
Automating user creation and management with Bash scripting not only streamlines administrative tasks but also enhances system security and operational efficiency in Linux environments. By understanding and customizing the script presented in this article, you can adapt it to meet specific organizational needs and scale your user management processes effectively.

Interested in gaining hands-on experience like this? Consider joining the [HNG Tech Internship Program](https://hng.tech/internship) where you can explore more projects like this, build practical skills, and collaborate with a vibrant community of tech enthusiasts.

Looking to hire skilled tech professionals or collaborate on future projects? Visit [HNG Tech Hire](https://hng.tech/hire) to connect with talented individuals ready to contribute to your team's success.

Take the next step in your tech journey with HNG Tech!

Feedback and Further Exploration
Have you automated user management tasks using Bash scripting? What challenges did you encounter, and how did you overcome them? Share your insights and experiences in the comments below!

💖 💪 🙅 🚩
jic
Justice Obioha (JIC)

Posted on July 3, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related