Automating User Management with Bash Scripting
Published: 2024-07-03 19:00:31

As a SysOps engineer, managing user accounts efficiently is crucial. In this article, we will discuss how to automate the creation of users and groups using a bash script (create_users.sh).

**Introduction**
The create_users.sh script automates the creation of user accounts based on input from a text file. It handles the setup of home directories, password generation, group management, and logging, making it ideal for scaling user management tasks. This script is a practical example of how to streamline user management processes while ensuring security and compliance.

**Script Overview**
Parsing Input
The script reads from a formatted text file where each line specifies a username and associated groups separated by semicolons. This approach allows for easy configuration and bulk user management.

**User and Group Creation**
The script checks if users and groups already exist, creates them if they don't, and assigns appropriate permissions and ownerships. This ensures that new users are correctly set up and integrated into the system.

**Password Security**
Passwords are securely generated using OpenSSL's base64 random generator and stored in /var/secure/user_passwords.txt, accessible only to the script owner. This step is crucial for maintaining the confidentiality of user credentials.

**Error Handling**
The script gracefully handles errors such as existing users or groups and logs these events to /var/log/user_management.log for audit purposes. This ensures transparency and accountability in user management.


Step-by-Step Implementation
Initialize Variables and Files
The script starts by defining log and password file paths and ensuring they exist with the correct permissions:

`#!/bin/bash

# Ensure the secure directory exists
sudo mkdir -p /var/secure
sudo touch /var/secure/user_passwords.txt

LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

# Ensure log and password files exist
sudo touch "$LOG_FILE"
sudo touch "$PASSWORD_FILE"

# Set permissions to secure the password file
sudo chmod 600 "$PASSWORD_FILE"
`

**Processing Each Line**
The script processes each line of the input file, trimming whitespace and extracting usernames and groups:

`while IFS=';' read -r username groups || [ -n "$username" ]; do
    username=$(echo "$username" | tr -d '[:space:]')
    groups=$(echo "$groups" | tr -d '[:space:]')

    # Debugging line to understand how each line is processed
    echo "Processing: username=$username, groups=$groups"
`

User and Group Creation
It checks if users and groups already exist and creates them if necessary:

```    if id "$username" &>/dev/null; then
        echo "$(date) - User '$username' already exists. Skipping creation." | sudo tee -a "$LOG_FILE"
        continue
    fi

    if ! getent group "$username" &>/dev/null; then
        echo "$(date) - Creating group '$username'." | sudo tee -a "$LOG_FILE"
        sudo groupadd "$username"
    fi

```
Assigning Users to Groups
The script assigns users to the specified groups:

```
    IFS=',' read -ra group_array <<< "$groups"

    for group in "${group_array[@]}"; do
        if ! getent group "$group" &>/dev/null; then
            echo "$(date) - Creating group '$group'." | sudo tee -a "$LOG_FILE"
            sudo groupadd "$group"
        fi
    done

    echo "$(date) - Creating user '$username'." | sudo tee -a "$LOG_FILE"
    sudo useradd -m -g "$username" -G "$(IFS=','; echo "${group_array[*]}")" "$username"

```

Password Generation and Assignment
Passwords are generated and assigned to users, and securely stored:

```
    password=$(openssl rand -base64 12)
    echo "$username:$password" | sudo chpasswd
    echo "$username,$password" | sudo tee -a "$PASSWORD_FILE"

    echo "$(date) - User '$username' created and assigned to groups: ${group_array[*]}." | sudo tee -a "$LOG_FILE"
done < "$1"

echo "$(date) - Script execution completed." | sudo tee -a "$LOG_FILE"

```

Security Considerations
User passwords are generated securely and stored in a protected file to prevent unauthorized access. Proper permissions ensure that sensitive information remains confidential.

Conclusion
Automating user management tasks with create_users.sh improves operational efficiency and reduces human error in user account provisioning. This script exemplifies best practices in DevOps for maintaining a secure and organized user environment.
By implementing create_users.sh, SysOps teams can streamline user management processes while ensuring security and compliance.

For more details about HNG internship, visit [HNG Internship](https://hng.tech/internship) or click to know more https://hng.tech