Automating User Creation and Management with a Bash Script
Published: 2024-07-01 12:51:36

In this article, we'll walk through a bash script that reads user information from a text file, creates users and their groups, sets up home directories, generates random passwords, logs actions, and stores passwords securely.

**Bash Script: create_users.sh**

```
#!/bin/bash

# Define file paths
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
INPUT_FILE=$1

# Ensure secure directory for passwords
mkdir -p /var/secure
chmod 700 /var/secure

# Function to generate random password
generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}

# Ensure log file exists
touch $LOG_FILE
chmod 644 $LOG_FILE

# Ensure password file exists
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

# Read input file
if [[ ! -f "$INPUT_FILE" ]]; then
    echo "Input file not found!" | tee -a $LOG_FILE
    exit 1
fi

# Process each line in the input file
while IFS=";" read -r username groups; do
    # Trim whitespaces
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)

    # Check if user already exists
    if id -u "$username" >/dev/null 2>&1; then
        echo "User $username already exists. Skipping." | tee -a $LOG_FILE
        continue
    fi

    # Create personal group for the user
    groupadd "$username"

    # Create user with personal group
    useradd -m -g "$username" "$username"
    if [[ $? -ne 0 ]]; then
        echo "Failed to create user $username." | tee -a $LOG_FILE
        continue
    fi

    # Create additional groups and add user to them
    IFS=',' read -ra ADDR <<< "$groups"
    for group in "${ADDR[@]}"; do
        group=$(echo $group | xargs)
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
        fi
        usermod -aG "$group" "$username"
    done

    # Generate random password and set it
    password=$(generate_password)
    echo "$username:$password" | chpasswd

    # Log user creation
    echo "Created user $username with groups $groups." | tee -a $LOG_FILE
    echo "$username,$password" >> $PASSWORD_FILE
done < "$INPUT_FILE"

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

```
When working as a SysOps engineer, managing user accounts and groups is a routine but crucial task. Automating this process not only saves time but also reduces the potential for errors.

Features:
1.**_Input File Processing_**
: The script takes a text file where each line contains a username and a list of groups, separated by a semicolon (;). Example:

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

2.**_User and Group Creation_**: For each user, the script creates a personal group with the same name as the username and adds the user to the specified groups.

3.**_Home Directory Setup_**: Home directories are created automatically with appropriate permissions.

4.**_Random Password Generation_**: A secure random password is generated for each user.

5.**_Logging Actions_**: All actions performed by the script are logged to `/var/log/user_management.log`

6.**_Secure Password Storage_**: Usernames and passwords are stored in `/var/secure/user_passwords.txt` with restricted access permissions.

**Script Breakdown:**

1.**_File Paths and Secure Directory Setup:_**

```
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
INPUT_FILE=$1
mkdir -p /var/secure
chmod 700 /var/secure

```

2.**_Random Password Generation Function_:**

```
generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}

```

3.**_Log and Password File Initialization:
_**
```
touch $LOG_FILE
chmod 644 $LOG_FILE
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

```

4.**_Processing the Input File_**:

```
if [[ ! -f "$INPUT_FILE" ]]; then
    echo "Input file not found!" | tee -a $LOG_FILE
    exit 1
fi

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

    if id -u "$username" >/dev/null 2>&1; then
        echo "User $username already exists. Skipping." | tee -a $LOG_FILE
        continue
    fi

    groupadd "$username"

    useradd -m -g "$username" "$username"
    if [[ $? -ne 0 ]]; then
        echo "Failed to create user $username." | tee -a $LOG_FILE
        continue
    fi

    IFS=',' read -ra ADDR <<< "$groups"
    for group in "${ADDR[@]}"; do
        group=$(echo $group | xargs)
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
        fi
        usermod -aG "$group" "$username"
    done

    password=$(generate_password)
    echo "$username:$password" | chpasswd

    echo "Created user $username with groups $groups." | tee -a $LOG_FILE
    echo "$username,$password" >> $PASSWORD_FILE
done < "$INPUT_FILE"

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

```

This script ensures efficient user management and enhances security through automated processes. For more insights, explore further learning opportunities, check out the [HNG Internship](https://hng.tech/internship) and [HNG Premium]( https://hng.tech/premium) website. You won't regret it