Bash Script Automation for User and Group Management in Linux
Tags: webdev, bash, automation, devops
Published: 2024-07-05 01:40:14

Managing user onboarding in a corporate environment can be complex, especially with a large influx of new employees. Manual assignment of users to directories, groups, and configuring permissions can lead to errors and consume valuable time. To streamline this process and ensure efficient onboarding, I've developed a Bash script that automates these tasks, providing a seamless deployment solution.

**Overview of the Script
**
The Bash script automates several critical tasks:

- User and Group Management: Reads user details from an input file, creates user accounts, and manages groups as specified.

- Password Management: Generates random passwords securely stored in /var/secure/user_passwords.txt with appropriate permissions.

- Logging: Records all script actions, including successes and errors, in /var/log/user_management.log for auditing purposes.

**THE SCRIPT
**
```
#!/bin/bash

# Log file and secure passwords file
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

# Ensure the log file and secure passwords file exist with correct permissions
sudo mkdir -p /var/secure
sudo touch "$PASSWORD_FILE"
sudo chmod 600 "$PASSWORD_FILE"
sudo touch "$LOGFILE"
sudo chmod 600 "$LOGFILE"

# Function to generate a random password
generate_password() {
    openssl rand -base64 12
}

# Check if openssl is installed
if ! command -v openssl &> /dev/null; then
    echo "openssl is required but not installed. Please install it and try again." >&2
    exit 1
fi

# Read the input file line by line
while IFS=';' read -r username groups; do
    # Remove any leading or trailing whitespace
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

    # Create a personal group with the same name as the username
    if ! getent group "$username" > /dev/null 2>&1; then
        if sudo groupadd "$username"; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - Group '$username' created." >> "$LOGFILE"
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') - Error creating group '$username'." >> "$LOGFILE"
            continue
        fi
    else
        echo "$(date '+%Y-%m-%d %H:%M:%S') - Group '$username' already exists." >> "$LOGFILE"
    fi

    # Create the user if it does not exist
    if ! id -u "$username" > /dev/null 2>&1; then
        if sudo useradd -m -s /bin/bash -g "$username" "$username"; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - User '$username' created." >> "$LOGFILE"

            # Generate a random password for the user
            password=$(generate_password)
            echo "$username:$password" | sudo chpasswd
            echo "$username:$password" | sudo tee -a "$PASSWORD_FILE" > /dev/null

            # Set ownership and permissions for the user's home directory
            sudo chown "$username":"$username" "/home/$username"
            sudo chmod 700 "/home/$username"

            echo "$(date '+%Y-%m-%d %H:%M:%S') - Password for '$username' set and stored securely." >> "$LOGFILE"
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') - Error creating user '$username'." >> "$LOGFILE"
            continue
        fi
    else
        echo "$(date '+%Y-%m-%d %H:%M:%S') - User '$username' already exists." >> "$LOGFILE"
    fi

    # Add user to additional groups
    IFS=',' read -ra group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        group=$(echo "$group" | xargs)
        if ! getent group "$group" > /dev/null 2>&1; then
            if sudo groupadd "$group"; then
                echo "$(date '+%Y-%m-%d %H:%M:%S') - Group '$group' created." >> "$LOGFILE"
            else
                echo "$(date '+%Y-%m-%d %H:%M:%S') - Error creating group '$group'." >> "$LOGFILE"
                continue
            fi
        fi
        if sudo usermod -aG "$group" "$username"; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - User '$username' added to group '$group'." >> "$LOGFILE"
        else
            echo "$(date '+%Y-%m-%d %H:%M:%S') - Error adding user '$username' to group '$group'." >> "$LOGFILE"
        fi
    done
done < "$1"

echo "User creation process completed."
exit 0

```

**Script Breakdown
**

```
#!/bin/bash

# Log file and secure passwords file
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

# Ensure the log file and secure passwords file exist with correct permissions
sudo mkdir -p /var/secure
sudo touch "$PASSWORD_FILE"
sudo chmod 600 "$PASSWORD_FILE"
sudo touch "$LOGFILE"
sudo chmod 600 "$LOGFILE"

# Function to generate a random password
generate_password() {
    openssl rand -base64 12
}

# Check if openssl is installed
if ! command -v openssl &> /dev/null; then
    echo "openssl is required but not installed. Please install it and try again." >&2
    exit 1
fi

# Read the input file line by line
while IFS=';' read -r username groups; do
    # Remove any leading or trailing whitespace
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)
```
**Initialization and File Setup 
**
Purpose: Sets up necessary files (user_passwords.txt and user_management.log) with secure permissions.
Explanation: Creates directories and files if they don't exist, ensuring only privileged access (600 permissions) for security.

```
# Function to generate a random password
generate_password() {
    openssl rand -base64 12
}

```
Random Password Generation:

Purpose: Provides a function to create strong, random passwords for new user accounts.
Explanation: Uses OpenSSL to generate a 12-character random password encoded in base64 format, ensuring security and complexity for user accounts.

```
# Check if OpenSSL is installed
if ! command -v openssl &> /dev/null; then
    echo "Error: OpenSSL is required but not installed. Please install it and try again." >&2
    exit 1
fi

```
**Dependency Check (OpenSSL):
**
Purpose: Ensures the script can use OpenSSL for generating passwords securely.
Explanation: Checks if OpenSSL is installed (command -v openssl &> /dev/null). If not, it outputs an error message and stops script execution, ensuring all dependencies are met before proceeding.

```
# Process each line from the input file
while IFS=';' read -r username groups; do
    # Trim whitespace from username and groups
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

```

**Input Processing (User and Group Management):
**
Purpose: Reads user details from an input file, cleans up whitespace, and manages user and group creation.
Explanation: Reads each line of the input file, splitting data into username and groups. It trims any leading or trailing whitespace (xargs), preparing data for user and group management tasks.

**To successfully run this script, follow these steps:
**
Ensure the script is Executable:
`chmod +x create_users.sh`

Run the Script with Sudo:
`sudo ./create_users.sh`

Reading the Input File (users.txt): The script reads each line from the input file containing usernames and groups separated by a semicolon. Multiple groups are separated by commas.

Example Input File (users.txt):

```
light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
```

Note: This input creates users Light,idimma, and Mayowa assigning them to the specified groups.

**Conclusion
**

In conclusion, this Bash script exemplifies how automation simplifies complex tasks such as user and group management in Linux environments. By leveraging shell scripting, administrators can achieve consistency, security, and efficiency across system deployments.

For places where you can grow your tech.skills and get hands-on projects, please visit:

https://hng.tech/internship 
OR
https://hng.tech/hire