Automating User Management with Bash: A Streamlined Approach
Published: 2024-07-04 13:24:03

**Introduction**
As a SysOps engineer, efficiently managing user accounts is crucial, especially when onboarding new developers. Automating this process saves time and reduces errors. In this article, I'll explain a Bash script, `create_users.sh` , designed to automate user creation, group assignment, secure password management, and comprehensive logging for troubleshooting and verification. This task was part of the DevOps track for the _HNG11 internship_.

---
**Script Overview**
The `create_users.sh` script reads a text file(`users.txt`) passed as an argument, containing usernames and group names. It creates users and groups, sets up home directories, generates random passwords, and logs all actions to `/var/log/user_management.log`.The generated passwords are securely stored in `/var/secure/user_passwords.txt`.

---
**Challenges and Solutions**

1. **Root Privileges**:Ensuring the script runs with root privileges is essential for creating users and modifying system files.

- **Solution**:The script checks for root privileges at the start and exits if not run as root.

2.**Handling Input Files**:Verifying that an input file is provided is crucial to prevent errors.

- **Solution**:The script checks if an input file is provided and exits with an error message if not.

3.**Secure Password Management**:Generating and storing passwords securely while ensuring only root can access them.

- **Solution**:The script uses `dev/urandom` to generate random passwords and stores them in a file with strict permissions.

4.**Logging**:Maintaining a log of all actions for transparency and troubleshooting.

- **Solution**:The script logs all to `/var/log/user_management.log`.

---
**Script Breakdown**

1. **Check Administrative Privilege**
The script starts by verifying the user has root privileges, ensuring it can perform all necessary actions without encountering permission issues.

```
if (( "$UID" != 0 )); then
    echo "Script requires root accessibility"
    exit 1
fi

```

2.**Check Input File**
It verifies that an input file is provided and exits with an error message if not.

```
if [ -z "$1" ]; then
  echo "Error: No file was provided"
  echo "Usage: $0 <name-of-text-file>"
  exit 1
fi

```

3.**Setup Log and Secure Password Files**
Ensures the log and password files exist, creating them if necessary, and sets appropriate permissions.

```
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
mkdir -p /var/secure
touch $LOG_FILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

```

4.**Generate Random Passwords**
Defines a function to generate random passwords for the users.

```
generate_random_password() {
    local length="${1:-12}"
    tr -dc 'A-Za-z0-9!?%+=' < /dev/urandom | head -c "$length"
}

```

5.**Process Each Line in the Input File**
Reads the input file, processes each line, and creates users and groups as specified. It also logs every action for transparency and troubleshooting.

```
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}

create_user() {
    local username=$1
    local groups=$2

    if getent passwd "$username" > /dev/null; then
        log_message "User $username already exists"
    else
        useradd -m "$username"
        log_message "Created user $username"
    fi

    # Add user to specified groups
    IFS=',' read -r -a group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        if ! getent group "$group" > /dev/null; then
            groupadd "$group"
            log_message "Created group $group"
        fi
        usermod -aG "$group" "$username"
        log_message "Added user $username to group $group"
    done

    # Set up home directory permissions
    chmod 700 /home/"$username"
    chown "$username:$username" /home/"$username"
    log_message "Set up home directory for user $username"

    # Generate a random password
    password=$(generate_random_password 12)
    echo "$username:$password" | chpasswd
    echo "$username,$password" >> $PASSWORD_FILE
    log_message "Set password for user $username"
}

while IFS=';' read -r username groups; do
    create_user "$username" "$groups"
done < "$1"

log_message "User creation process completed."

```
**Conclusion**
The `create_users.sh` script automates the process of user creation, group assignment, and secure password management, ensuring efficiency and reducing potential errors. This approach is essential for SysOps engineers managing large teams.
This project is part of the _HNG Internship program_, which aims to train and nurture aspiring tech professionals. To learn more about the _HNG Internship_, visit https://hng.tech/internship and https://hng.tech/hire.

Thanks for reading!