DEV Community

Cover image for Automating User Creation with Bash Script
Victor Oderinde
Victor Oderinde

Posted on

Automating User Creation with Bash Script

As a SysOps engineer, managing users and groups in a growing development team can be a time-consuming task. To streamline this process, automating user and group creation with a Bash script can save valuable time and reduce errors. This article will guide you through creating a script to automate these tasks, while ensuring secure handling of user passwords and detailed logging of all actions.

In this article, we will explore an enhanced bash script that handles user creation and management for your growing company. This script reads a formatted text file and handles user and group creation, sets up home directories, generates random passwords, and ensures secure logging of actions. This script allows for multiple groups per user to be added when the user is created.

Requirements

  • Linux machine - Ubuntu preferably
  • Sudo privileges: a type of administrator right to run higher level commands.
  • A Text file containing the users and groups separated by a ;

Key Features

  1. Reads Input File: The script reads a text file(.txt) where the user and group is inserted in each line of the file as user;group1,group2,group3
  2. Creates Users and Groups: Each user gets a personal group and additional groups as specified.
  3. Sets Up Home Directories: Sets up home directories with proper permissions.
  4. Generates Random Passwords: Securely generates and stores random passwords.
  5. Log Actions: Logs all action to /var/log/user_management.log and stores generated passwords securely in /var/secure/user_passwords.txt. You can specify your custom paths.

Let's Get this Done

Create a file with .sh extension. Here I the script called create_users.sh

Create user

The create_users.sh script is divided into several modules, each responsible for a specific task. Here's a detailed explanation of each module:

1. Initialization

#!/bin/bash

# Script to create users and groups from a file, generate passwords, and log actions

INPUT_FILE=$1
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
DATE=$(date "+%Y-%m-%d %H:%M:%S")

Enter fullscreen mode Exit fullscreen mode
  • #!/bin/bash called Shebang: Specifies the script should be run using the Bash shell.
  • $1 is the Input Arguments: Takes the name of the input file as the first argument.
  • PASSWORD_FILE: Log and Password Files- Defines paths for logging and storing passwords.
  • DATE: Captures the current date and time for logging purposes.

2. Setup Directories and Files

## Ensure the log and password directories exist
sudo mkdir -p /var/log
sudo mkdir -p /var/secure
sudo touch $LOG_FILE
sudo touch $PASSWORD_FILE

# Set permissions for the password file
sudo chmod 600 $PASSWORD_FILE
Enter fullscreen mode Exit fullscreen mode
  • mkdir: directory creation which ensures that the directories for logs and secure files exist.
  • touch: file creation that creates the log file and password file if they don't exist.
  • chmod: File Permissions used to set the password file to be readable and writable only by the owner (chmod 600).

3. Logging Function

# Function to log actions
log_action() {
    echo "$DATE - $1" | sudo tee -a $LOG_FILE > /dev/null
}
Enter fullscreen mode Exit fullscreen mode
  • log_action: Defines a function to log actions with timestamps to the log file. The sudo tee -a $LOG_FILE command appends the log message to the log file.

4. Password Generation Function

# Function to generate a random password
generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12 ; echo ''
}
Enter fullscreen mode Exit fullscreen mode
  • generate_password: Uses the tr command to generate a random 12-character password consisting of alphanumeric characters.

5. Input Validation

# Ensure input file is provided
if [[ -z "$INPUT_FILE" ]]; then
    echo "Usage: $0 <input_file>"
    log_action "ERROR: No input file provided"
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode
  • Validation: Checks if the input file is provided. If not, logs an error and exits the script.

6. Main Processing Loop

# Read the input file line by line
while IFS=';' read -r username groups; do

    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

    # Ignore empty lines
    if [[ -z "$username" ]]; then
        continue
    fi
Enter fullscreen mode Exit fullscreen mode
  • Reading Input: Reads the input file line by line, splitting each line into username and groups based on the ; delimiter.
  • Trimming Whitespace: Uses xargs to trim any leading or trailing whitespace from username and groups.
  • Ignore Empty Lines: Skips processing for empty lines.

7. User and Group Creation

    # Check if user already exists
    if id "$username" &>/dev/null; then
        log_action "User $username already exists"
        continue
    fi

    # Create the user with their own personal group
    user_group=$username
    if ! getent group "$user_group" > /dev/null; then
        sudo groupadd "$user_group"
        log_action "Created group $user_group"
    fi

    sudo useradd -m -g "$user_group" -s /bin/bash "$username"
    log_action "Created user $username with group $user_group"
Enter fullscreen mode Exit fullscreen mode
  • User Existence Check: Uses the id command to check if the user already exists. If the user exists, it logs the action and skips to the next iteration.
  • Personal Group Creation: Checks if a group with the same name as the username exists. If not, it creates the group.
  • User Creation: Creates the user with their personal group, sets the shell to Bash, and creates a home directory.

8. Password Handling

    # Generate a random password
    password=$(generate_password)
    echo "$username:$password" | sudo chpasswd
    log_action "Set password for user $username"

    # Store the password securely
    echo "$username,$password" | sudo tee -a $PASSWORD_FILE > /dev/null
Enter fullscreen mode Exit fullscreen mode
  • Password Generation: Generates a random password using the generate_password function.
  • Password Assignment: Sets the generated password for the user using chpasswd.
  • Password Storage: Appends the username and password to the password file in txt format.

9. Additional Group Handling

    # Handle additional groups
    IFS=',' read -ra ADD_GROUPS <<< "$groups"
    for group in "${ADD_GROUPS[@]}"; do
        group=$(echo "$group" | xargs)
        if ! getent group "$group" > /dev/null; then
            sudo groupadd "$group"
            log_action "Created group $group"
        fi
        sudo usermod -aG "$group" "$username"
        log_action "Added user $username to group $group"
    done
Enter fullscreen mode Exit fullscreen mode
  • Parsing Groups: Splits the groups string into an array using , as the delimiter.
  • Group Existence Check: Checks if each group exists and creates it if necessary.
  • User Group Assignment: Adds the user to each additional group using usermod -aG.

10. Home Directory Permissions

    # Set appropriate permissions and ownership for the home directory
    sudo chown -R "$username:$user_group" "/home/$username"
    sudo chmod 700 "/home/$username"
    log_action "Set permissions for home directory of user $username"
done < "$INPUT_FILE"

log_action "User creation process completed"
Enter fullscreen mode Exit fullscreen mode
  • Ownership and Permissions: Sets the ownership of the user's home directory to the user and their personal group. Sets directory permissions to 700 (owner can read, write, and execute; others have no permissions).

Execute

Merge the modules above into the script (in my case create_user.sh). Give execute permission to the file using sudo chmod +x create_user.sh. and run the script like the below

Execute command format

  • PS: you specify the path and the name of your custom .txt file you create in your machine with the content in the format below

file text sample

Conclusion

By modularizing the script, each part of the process is handled in a clear and structured manner, making it easier to understand and maintain. This script efficiently automates user and group management tasks, ensuring secure handling of passwords and detailed logging of actions.

For more resources and opportunities to enhance your technical skills, check out the HNG Internship and explore their premium offerings. The HNG Internship is a great platform to learn, grow, and network with industry professionals.

Top comments (0)