Linux Bash Script User Creation
Published: 2024-07-03 19:06:07

Hi Enthusiast DevOps Engineer,

   Today we'll be having a deep insight on the need to write an automated **users bash script** in an organization, and also having all the metrics and password auto generated stored in a LOG_FILE.

The main reason for the creation of the **users bash scrip** is to mitigate repetitive user/group creation task manually, which might be daunting in most cases, and also to have an autonomous control of employees who have assess to the organization Linux workflow environment.

Before i proceed, the user bash script creation is in curtesy of (**HNG Internship**) program, which has just kicked off for the year 2024 "11th cohort", helping various beginners and intermediate tech enthusiast in having a real world project experience. To learn more about HNG internship program, kindly visit {% embed https://hng.tech/internship %}, {% embed https://hng.tech/premium %}.

Now lets delve to the business of the day, seat back, make use of your seat belt, while we journey through this together.

Firstly, we'll create a text file called `users` filled with the content below, which is dependent on our bash script file to execute its functions.

```
light; sudo,dev,www-data
 idimma; sudo
 mayowa; dev,www-data
 dmex; devops,sysops
 iosegbo; sysops
```

Secondly we'll be creating a file called `create_users.sh` which will run as our bash script file with the code below


```
#!/bin/bash

# Autogenerate Password and Metrics will be sent here
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"


# This will create a /var/secure file, and also assign a <write, read & execution> permission to the created file.
mkdir -p /var/secure
chmod 700 /var/secure

# Create or clear the log and password files
> $LOG_FILE
> $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

# Function to generate random password
generate_password() {
    echo $(openssl rand -base64 12)
}


# Read the input file, which is the <users> file we created to be dependent on our bash script code function execution
INPUT_FILE=$1
# Process each line in the file
while IFS= read -r line; do
  # Ignore characters before the semicolon
  after_semicolon="${line#*;}"

  # Split the line into items separated by commas
  IFS=',' read -ra items <<< "$after_semicolon"

  # Ensure a group exists for each item
  for item in "${items[@]}"; do
    item=$(echo "$item" | xargs)  # Trim whitespace
    if [ ! -z "$item" ]; then
      if ! getent group "$item" > /dev/null; then
        echo "Creating group: $item"
        sudo groupadd "$item"
      else
        echo "Group already exists: $item"
      fi
    fi
  done
done < "$INPUT_FILE"


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


    # Create user with home directory and primary group
    if ! id "$user" &>/dev/null; then
        useradd -m "$user"
        echo "User $user was created successfully." >> $LOG_FILE
    else
        echo "User $user already exists." >> $LOG_FILE
    fi

    # Set user's groups
    if [ -n "$groups" ]; then
        usermod -aG $groups "$user"
        echo "User $user added to group: $groups." >> $LOG_FILE
    fi

    # Auto Generate and set password
    password=$(generate_password)
    echo "$user:$password" | chpasswd
    echo "$user,$password" >> $PASSWORD_FILE
    echo "Password for user $user set." >> $LOG_FILE


done < "$INPUT_FILE"

```

Thirdly, we'll have to assign an execution permission to the created bash script file `chmod 700 create_users.sh`

Lastly, the command to execute our bash script file is

`sudo ./create_users.sh users` 

The command above will execute the above bash script function which is written as a code, enabling all the users to be assigned to the specified group and also enabling each users to have an assigned encrypted password which will be redirected or logged to a `LOG_FILE` encoded in the script.


Here are the list of commands to execute on our Linux VM to check the following output of our bash script block of code

**sudo cat /var/log/user_management.log** (This cmd checks for the activities which has taken place in the course of the bash script execution i.e "MERTICS").

**sudo cat /var/secure/user_passwords.txt** (This cmd checks for the auto generated password assigned to each users).

To confirm validity of your user creation, simply execute the following command below

`su dmex`

Then copy the encrypted password generated for `dmex` under **sudo cat /var/secure/user_passwords.txt**



Thank you for taking your time in reading through to the completion of the blog post, do have a wonderful time.