DEV Community

Cover image for Automated User Management with Bash Script
Tesleem Amuda
Tesleem Amuda

Posted on • Edited on

Automated User Management with Bash Script

Managing user accounts in a Linux environment can be tedious, especially when dealing with a large number of new employees. To simplify this process, we can use a Bash script to automate user and group creation, ensuring appropriate permissions and logging. Below is a detailed breakdown of a Bash script that accomplishes this.



Script Overview


The script reads a text file containing usernames and group names, creates users and groups as specified, sets up home directories with appropriate permissions and ownership, generates random passwords for the users, and logs all actions to /var/log/user_management.log. It also securely stores the generated passwords in /var/secure/user_passwords.txt.



Script Breakdown


#!/bin/bash

# Check if the input file is provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 <user_list_file>"
    exit 1
fi

user_list_file="$1"

# Log and password file paths
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"

# Create the necessary directories and set permissions
mkdir -p /var/log
mkdir -p /var/secure
touch "$log_file"
touch "$password_file"
chmod 600 "$password_file"
Enter fullscreen mode Exit fullscreen mode

Input File Check: The script starts by ensuring that an input file is provided. This file should contain the list of users to be managed.
Directory and File Setup: It creates directories and files necessary for logging and storing passwords. Permissions are set to ensure security.

# Function to log actions
log_action() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$log_file"
}
Enter fullscreen mode Exit fullscreen mode

Logging Function: A function log_action is defined to log each action taken by the script. This helps in auditing and troubleshooting.

# Read the user list file
while IFS=';' read -r username groups; do
    # Remove whitespace
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)
Enter fullscreen mode Exit fullscreen mode

Reading the User List: The script reads each line from the input file, expecting a username and groups separated by a semicolon. Whitespace is trimmed to ensure clean data.

    # Ensure all specified groups exist
    for group in $(echo "$groups" | tr ',' ' '); do
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
            if [ $? -eq 0 ]; then
                log_action "Created group $group"
            else
                log_action "Failed to create group $group"
                continue
            fi
        else
            log_action "Group $group already exists"
        fi
    done
Enter fullscreen mode Exit fullscreen mode

Group Management: The script checks if each specified group exists and creates it if it doesn't. Actions are logged accordingly.

    # Create the personal group
    if ! getent group "$username" >/dev/null; then
        groupadd "$username"
        if [ $? -eq 0 ]; then
            log_action "Created group $username"
        else
            log_action "Failed to create group $username"
            continue
        fi
    else
        log_action "Group $username already exists"
    fi
Enter fullscreen mode Exit fullscreen mode

Personal Group Creation: For each user, a personal group with the same name is created if it doesn't already exist.

    # Create the user with the personal group
    if ! id -u "$username" >/dev/null 2>&1; then
        useradd -m -g "$username" -s /bin/bash "$username"
        if [ $? -eq 0 ]; then
            log_action "Created user $username with personal group $username"
Enter fullscreen mode Exit fullscreen mode

User Creation: If the user doesn't already exist, the script creates the user account, assigns the personal group, and sets the default shell to bash.

            # Set the user's additional groups
            if [ -n "$groups" ]; then
                usermod -aG "$groups" "$username"
                if [ $? -eq 0 ]; then
                    log_action "Added user $username to groups $groups"
                else
                    log_action "Failed to add user $username to groups $groups"
                fi
            fi

            # Generate a random password
            password=$(openssl rand -base64 12)
            echo "$username:$password" | chpasswd
            if [ $? -eq 0 ]; then
                log_action "Set password for user $username"
            else
                log_action "Failed to set password for user $username"
            fi

            # Save the password securely
            echo "$username,$password" >> "$password_file"
        else
            log_action "Failed to create user $username"
        fi
    else
        log_action "User $username already exists"
    fi
Enter fullscreen mode Exit fullscreen mode

Additional Group Assignment: If additional groups are specified, the user is added to these groups.
Password Management: A random password is generated and set for the user. The password is stored securely in a file with restricted permissions.

    # Set home directory permissions
    chmod 700 "/home/$username"
    chown "$username:$username" "/home/$username"
    log_action "Set permissions for /home/$username"
done < "$user_list_file"

log_action "Script execution completed."
Enter fullscreen mode Exit fullscreen mode

Home Directory Permissions: The script sets strict permissions on the user's home directory to ensure privacy and security.



Key Features

  1. Group Creation: Ensures all specified groups exist before assigning users to them, preventing errors and ensuring proper group membership.
  2. User Creation: Creates users with personal groups and sets up their home directories with appropriate permissions.
  3. Password Generation: Generates random, secure passwords for new users and stores them securely.
  4. Logging: Logs all actions to a log file for audit purposes and troubleshooting.



Conclusion


This script is a robust solution for managing user accounts in a Linux environment. By automating the creation and management of users and groups, it saves time and reduces the potential for errors.

Top comments (1)