DEV Community

Cover image for Automating User Account Management in Linux with a Bash Script
Olatunji
Olatunji

Posted on

Automating User Account Management in Linux with a Bash Script

User Management is an integral part of a Sys Ops Engineer, as this is useful in day-to-day activity. This is usually required when onboarding new members of staff. In this piece, we will go through the process of creating and assigning new users.

This is part of HNG Internship requirements. You can learn more about HNG by clicking on the link below.
HNG Internship

Premise

Manually handling user accounts can be tedious and often leads to mistakes. To make things easier and more reliable, we should automate this process. We'll create a script called "create_users.sh" that will read a list of usernames and groups from a given text file, create the users and groups, set up their home directories, generate random passwords, and log everything to a management.log file. This will save time, reduce errors, and keep things consistent.

Prerequisites

The following are the requirements needed to create and execute the script

  • Basic Knowledge of Linux command
  • Admin privilege
  • Text editor e.g Vim, Nano, TextEdit, etc

Overview

The script is expected to perform the following tasks

  1. Reads a list of users and groups from any given text file.
  2. Creates users and assigns them to specified groups.
  3. Set up home directories with appropriate permissions.
  4. Generates random passwords for the users.
  5. Logs all actions to /var/log/user_management.log.
  6. Stores the generated passwords securely in /var/secure/user_passwords.csv.

Procedure

  • Define the variable to accept the input file, log file and password file
INPUT_FILE="$1"
USER_INPUT_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"
Enter fullscreen mode Exit fullscreen mode
  • Create functions to perform tasks
# Function to log messages
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $USER_INPUT_FILE > /dev/null
}

# Function to generate random password
random_password() {    
    < /dev/urandom tr -dc 'A-Za-z0-9' | head -c 12
}

Enter fullscreen mode Exit fullscreen mode
  • Create directories, and files and give permissions
# Create neccessary directories if they do not exist
sudo mkdir -p /var/log
sudo mkdir -p /var/secure

# create log file if it does not exist, and set the neccessary permission
sudo touch $USER_INPUT_FILE
sudo chmod 600 $USER_INPUT_FILE

# create password file if it does not exist, and set the neccessary permission
sudo touch $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
Enter fullscreen mode Exit fullscreen mode
  • The code below read the file line by line, create the user, add to group and set password
# Read the input file line by line
while IFS=';' read -r username groups; do
    # Remove whitespace from username and group
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)

    # Create the new user 
    if id -u "$username" >/dev/null 2>&1; then
        log_message "User $username already exists. Creation skipped."
    else
        sudo useradd -m -s /bin/bash "$username"
        if [ $? -eq 0 ]; then
            log_message "New user: $username created successfully."
        else
            log_message "Unable to create user: $username."
            continue
        fi
    fi

    # Create the new user personal group
    if ! getent group "$username" >/dev/null 2>&1; then
        sudo groupadd "$username"
        log_message "Personal group $username created successfully"
    fi

    # Add user to group
    sudo usermod -aG "$username" "$username"

    # Add the user to other groups
    IFS=',' read -ra group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        group=$(echo $group | xargs) # Remove whitespace
        if ! getent group "$group" >/dev/null 2>&1; then
            sudo groupadd "$group"
            log_message "Group $group created."
        fi
        sudo usermod -aG "$group" "$username"
        log_message "User $username added to group: $group."
    done

    # Generate a random password and set it for the created user
    password=$(random_password)
    echo "$username:$password" | sudo chpasswd
    echo "$username,$password" | sudo tee -a $PASSWORD_FILE > /dev/null

    log_message "Password set for user $username."
done < "$INPUT_FILE"
Enter fullscreen mode Exit fullscreen mode
  • Log message to show the status after execution
log_message "User creation script completed."
echo "User creation process is complete. Check $USER_INPUT_FILE for details"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using a bash script to automate user account management can greatly simplify the onboarding process for new employees, users, or accounts. By following the steps outlined in this article, you can create an effective script that ensures users are created, added to groups, and provided with secure passwords, all while logging actions for transparency and audit purposes.

This tutorial is made possible by HNG.

You can find the bash code https://github.com/hollyphat/Hng11-Stage-1.

Top comments (0)