User Management Automation Using Bash Script
Tags: devops, automation, linux, bash
Published: 2024-07-04 12:53:00

## INTRODUCTION
As a SysOps (Systems Operations) engineer, managing user accounts and permissions is a critical task. Ensuring that users are properly created, assigned to the correct groups, and have secure passwords is essential for maintaining the security and efficiency of the system. A script file (`create_users.sh`) will be created to automate the process of user and group creation, making it easier to manage large numbers of users and maintain a secure environment. This is a stage 1 DevOps task given at the [HNG 11 INTERNSHIP PROGRAM](https://hng.tech/internship).

### Prerequisites
- Basic knowledge of the Linux CLI (command line interface).

Script Code:

```
#!/bin/bash


# Check if the script is run as root user
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root"
  exit 1
fi


# Check if the input file is provided in argument (contains the usernames and groups)
if [ -z "$1" ]; then
  echo "Usage: sudo $0 <filename>"
  exit 1
fi

INPUT_FILE=$1
LOG_FILE="/var/log/user_management.log"

# Create a secure directory to save secret files
mkdir -p /var/secure
chmod 700 /var/secure

# Create secure passwords file
PASSWORD_FILE="/var/secure/user_passwords.txt"
echo "USERNAME	|	PASSWORD" > "$PASSWORD_FILE"
echo "---------------------------------------------" >> "$PASSWORD_FILE"
chmod 600 "$PASSWORD_FILE"



# Read input file line by line
while IFS=';' read -r username groups; do

   # Remove leading/trailing whitespaces
     username=$(echo "$username" | xargs)
     groups=$(echo "$groups" | xargs)

   # Skip empty lines
     if [ -z "$username" ]; then
       continue
     fi


  # Create the user with a personal group
    if id "$username" &>/dev/null; then
      echo "----------------------------------------------------------------" | tee -a "$LOG_FILE"
      echo "User $username already exists" | tee -a "$LOG_FILE"
    else
      useradd -m -U "$username"
      echo "----------------------------------------------------------------" | tee -a "$LOG_FILE"
      echo "User $username created with a personal group" | tee -a "$LOG_FILE"
    fi


  # Create additional groups and assign the user to them
  if [ -n "$groups" ]; then
    IFS=',' read -ra groupName <<< "$groups"
    for group in "${groupName[@]}"; do
      group=$(echo "$group" | xargs)  # Remove leading/trailing whitespaces
      if ! getent group "$group" &>/dev/null; then
        groupadd "$group"
        echo "group: $group created successfully"
      fi
      usermod -aG "$group" "$username"
      echo "user: $username added to group: $group"
    done
  fi


    # Generate, set and store password securely
    password=$(openssl rand -base64 12)
    echo "$username:$password" | chpasswd
    echo "$username	|	$password" >> "$PASSWORD_FILE"



    # Set permissions and ownership for the home directory
    chown -R "$username":"$username" "/home/$username"
    chmod 700 "/home/$username"

    echo "-----------------------------------------------------------------------------------"
    echo "  "

    # Log recent actions
    echo "$(date '+%Y-%m-%d %H:%M:%S') - Created user with username: $username and groups: $groups" >> "$LOG_FILE"
    echo "-------------------------------------------------------------------" >> "$LOG_FILE"
done < "$INPUT_FILE"

```

### Key Features
**1. Automated User and Group Creation:**

- The script reads from a file containing user and group information and automates the creation of users and their respective groups.
- Personal groups are created for each user, ensuring clear ownership and security.
Group Assignment:
- Users can be assigned to multiple groups, facilitating organized and efficient permission management.

**2. Secure Password Generation:**

- Random passwords are generated for each user, enhancing security.
- Passwords are stored securely in a file with restricted access, ensuring that only authorized personnel can view them.

**3. Logging and Documentation:**

Actions performed by the script are logged to a file, providing an audit trail for accountability and troubleshooting.

### Usage:

**1 Input File:** The script takes an input file containing the list and users and groups they are to be added. it is formatted as `user;groups`

```
light; engineering,marketing,drama
idimma; drama,product
mayowa; hng-premium,design
```
**2. Script file:** You need to first make sure your script is executable by using this command `chmod +x create_users.sh`.
- Execute the script with root privileges to ensure it can create users and groups and manage passwords.

```
sudo bash create_users.sh <filename>
```
**3. Output:** 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dq3wb715s34io5co39cp.jpg)
- Passwords are securely stored in `/var/secure/user_passwords.txt`.
- All actions are logged to `/var/log/user_management.log`.




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrgrem4il8o1pqoeis6t.jpg)

You can checkout for available roles at HNG [here](https://hng.tech/hire) and register for the next [HNG Internship Cohort](https://hng.tech/internship)

Link to my script and file: https://github.com/ideateGudy/User-Management-Script-Using-Bash