Automating User Management on Ubuntu with Bash Scripting
Tags: devops, ubuntu, bash, linux
Published: 2024-07-04 04:20:56

In modern IT operations, efficient user management on Linux systems is pivotal for maintaining security and operational flow. Automating tasks such as user creation, group management, and password handling not only saves time but also enhances consistency and reduces errors. This article delves into how to achieve these automation goals using a Bash script (create_users.sh) specifically tailored for Ubuntu environments.

**Script Overview**
The create_users.sh script simplifies the complex task of managing user accounts through automation. It reads from an input file (user_list.txt), where each line specifies a username followed by associated groups. Upon execution, the script creates users, assigns them to specified groups, sets up their home directories with proper permissions, generates secure passwords, and logs all activities for accountability.

**Key Implementation Steps**
Input Parsing: The script efficiently parses input to extract usernames and their respective groups, disregarding unnecessary whitespace for cleaner processing.

User and Group Management: For each user entry:

Checks for existing users and creates new ones as needed.
Ensures groups are created if they do not already exist, then assigns users accordingly using administrative commands (useradd, groupadd, usermod).
Home Directory Setup: Post user creation, the script configures home directories under /home/username, ensuring appropriate permissions (chmod) and ownership (chown) are set for security and accessibility.

Password Security: Passwords are randomly generated using cryptographic standards (/dev/urandom) and securely stored in /var/secure/user_passwords.csv. This file restricts access to only authorized users, maintaining confidentiality.

Logging: All script actions, from user creation to password generation, are logged meticulously in /var/log/user_management.log. This log serves as a comprehensive audit trail, aiding troubleshooting and compliance efforts.

**Deployment Guide**
To deploy the create_users.sh script:

Clone the repository and navigate to the script directory.
Prepare the user_list.txt file with usernames and their respective groups.
Execute the script with root privileges (sudo bash create_users.sh user_list.txt).
Review logs in /var/log/user_management.log and access passwords securely stored in /var/secure/user_passwords.csv as needed.

**Detailed Script Overview**

The `create_users.sh` script simplifies the complex task of managing user accounts through automation. It reads from an input file (`user_list.txt`), where each line specifies a username followed by associated groups. Upon execution, the script creates users, assigns them to specified groups, sets up their home directories with proper permissions, generates secure passwords, and logs all activities for accountability.

**Key Implementation Steps**

1. **Input Parsing**: The script efficiently parses input to extract usernames and their respective groups, disregarding unnecessary whitespace for cleaner processing.

    ```bash
    #!/bin/bash

    LOGFILE="/var/log/user_management.log"
    PASSWORD_FILE="/var/secure/user_passwords.csv"

    if [ "$EUID" -ne 0 ]; then
        echo "Please run as root"
        exit 1
    fi

    if [ ! -f "$1" ]; then
        echo "Input file not found!"
        exit 1
    fi

    mkdir -p /var/secure
    touch "$PASSWORD_FILE"
    chmod 600 "$PASSWORD_FILE"

    while IFS=';' read -r username groups; do
        username=$(echo "$username" | xargs)
        groups=$(echo "$groups" | xargs)
    ```

2. **User and Group Management**: For each user entry:
   - Checks for existing users and creates new ones as needed.
   - Ensures groups are created if they do not already exist, then assigns users accordingly using administrative commands (`useradd`, `groupadd`, `usermod`).

    ```bash
        if id "$username" &>/dev/null; then
            echo "User $username already exists." | tee -a "$LOGFILE"
        else
            useradd -m "$username"
            echo "User $username created successfully." | tee -a "$LOGFILE"
        fi

        user_group="$username"
        if ! getent group "$user_group" &>/dev/null; then
            groupadd "$user_group"
            echo "Group $user_group created successfully." | tee -a "$LOGFILE"
        fi

        usermod -aG "$user_group" "$username"

        IFS=',' read -ra ADDR <<< "$groups"
        for group in "${ADDR[@]}"; do
            group=$(echo "$group" | xargs)
            if ! getent group "$group" &>/dev/null; then
                groupadd "$group"
                echo "Group $group created successfully." | tee -a "$LOGFILE"
            fi
            usermod -aG "$group" "$username"
            echo "Added $username to group $group." | tee -a "$LOGFILE"
        done
    ```

3. **Home Directory Setup**: Post user creation, the script configures home directories under `/home/username`, ensuring appropriate permissions (`chmod`) and ownership (`chown`) are set for security and accessibility.

    ```bash
        home_dir="/home/$username"
        if [ -d "$home_dir" ]; then
            chown "$username:$user_group" "$home_dir"
            chmod 755 "$home_dir"
            echo "Home directory $home_dir set up for $username." | tee -a "$LOGFILE"
        fi
    ```

4. **Password Security**: Passwords are randomly generated using cryptographic standards (`/dev/urandom`) and securely stored in `/var/secure/user_passwords.csv`. This file restricts access to only authorized users, maintaining confidentiality.

    ```bash
        password=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 12)
        echo "$username:$password" | chpasswd
        echo "$username,$password" >> "$PASSWORD_FILE"
        echo "Password set for $username." | tee -a "$LOGFILE"
    ```

5. **Logging**: All script actions, from user creation to password generation, are logged meticulously in `/var/log/user_management.log`. This log serves as a comprehensive audit trail, aiding troubleshooting and compliance efforts.

    ```bash
    done < "$1"

    echo "User creation process completed." | tee -a "$LOGFILE"
    ```

### Deployment Guide

#### Prerequisites

- Ubuntu environment with Bash shell.
- Root or sudo privileges to execute administrative commands (`useradd`, `groupadd`, `chmod`, `chown`).

#### Steps to Deploy

1. **Clone the Repository:**
   ```bash
   git clone https://github.com/EkeminiThompson/user_automation
   cd create_users
   ```

2. **Prepare Input File (`user_list.txt`):**
   Create a text file with usernames and their respective groups in the format specified.

3. **Run the Script:**
   Execute the script with root privileges:
   ```bash
   sudo bash create_users.sh user_list.txt
   ```

4. **Review Logs and Passwords:**
   - View detailed logs in `/var/log/user_management.log` to verify script execution.
   - Access generated passwords securely stored in `/var/secure/user_passwords.csv` as needed.


**Conclusion**
By automating user management tasks with create_users.sh, organizations can streamline operations, enhance security, and ensure consistency across Linux environments. This script exemplifies best practices in IT administration, empowering sysadmins to focus on strategic initiatives while maintaining robust user access controls.

**Resources**
[GitHub Repository:](https://github.com/EkeminiThompson/user_automation.git) Access the script and related files.
[HNG Internship:](https://hng.tech/internship) Learn more about opportunities in tech and automation.
[HNG Premium:](https://hng.tech/premium) Additional resources for professional growth and development.

About the Author
Ekemini Thompson is a seasoned Linux system administrator passionate about leveraging automation to optimize IT operations.