DEV Community

Clinton Ogechi
Clinton Ogechi

Posted on

User Creation Aumation in Linux with a Bash Script

Introduction

In the world of a SysOps engineer, one of the common tasks you will encouter is the creation and management of users and groups. Automation helps simplify this process, making it efficient and time saving. In this blog post, we'll go through a bash script createusers.sh that automates the creation of users and groups, set up home directories with appropriate permissions and ownership, generate random passwords for the users, and log all actions.

Breaking down the script

Here is the complete script created in create_users.sh with and an explanation of each section.

#!/bin/bash

# Define the log & password file variables
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Create and set permissions for log and password files
touch $LOG_FILE
mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

# Generate a random password for a user
generate_password() {
  tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}

# Check if the file is provided
if [ -z "$1" ]; then
  echo "Usage: $0 <user_file>"
  exit 1
fi
USER_FILE="$1"

# Process each line of the user file
while IFS=";" read -r username groups; do
  # Remove leading and trailing whitespace from username and groups
  username=$(echo $username | xargs)
  groups=$(echo $groups | xargs)

  # If a user does not exist, create user and personal group
  if ! id -u $username >/dev/null 2>&1; then
    useradd -m -s /bin/bash $username
    echo "$(date) - Created user: $username" >> $LOG_FILE

    # Generate a password for the user
    password=$(generate_password)
    echo "$username,$password" >> $PASSWORD_FILE
    echo "$username:$password" | chpasswd

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

    # Assign the user to the specified groups
    if [ -n "$groups" ]; then
      IFS=',' read -r -a group_array <<< "$groups"
      for group in "${group_array[@]}"; do
        if ! getent group $group >/dev/null; then
          groupadd $group
          echo "$(date) - Created group: $group" >> $LOG_FILE
        fi
        usermod -aG $group $username
        echo "$(date) - Added $username to group: $group" >> $LOG_FILE
      done
    fi
  else
    echo "$(date) - User $username already exists" >> $LOG_FILE
  fi
done < "$USER_FILE"
echo "The user creation process is completed."
Enter fullscreen mode Exit fullscreen mode

Explanation

Defining the log & password file variables: We define the paths for the log file and the password storage file. It also ensures that a secure directory for password storage is created with the neccesary permissions.

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

touch $LOG_FILE
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
Enter fullscreen mode Exit fullscreen mode

Processing the Input File: The script reads the input file provided. Each line is expected to have a username and a list of groups separated by a semicolon. The script processes each line, removing any leading or trailing whitespace from username and groups.

if [ -z "$1" ]; then
  echo "Usage: $0 <user_file>"
  exit 1
fi
USER_FILE="$1"

while IFS=";" read -r username groups; do
  # Remove leading and trailing whitespace from username and groups
  username=$(echo $username | xargs)
  groups=$(echo $groups | xargs)
Enter fullscreen mode Exit fullscreen mode

Generating Random Passwords: This script generates random passwords for each user using a secure method. These passwords are then stored in a directory; /var/secure/user_passwords.csv, with the neccesary file permissions set to ensure only the owner can read it.

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

Function to Create Users and Groups: This script creates each user and their group, as well as any additional groups. If the user or group already exists, the script logs a message and skips to the next entry. It sets up home directories with appropriate permissions and ownership.

if ! id -u $username >/dev/null 2>&1; then
    useradd -m -s /bin/bash $username
    echo "$(date) - Created user: $username" >> $LOG_FILE

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

    chown -R "$username:$username" "/home/$username"
    chmod 700 "/home/$username"

    if [ -n "$groups" ]; then
      IFS=',' read -r -a group_array <<< "$groups"
      for group in "${group_array[@]}"; do
        if ! getent group $group >/dev/null; then
          groupadd $group
          echo "$(date) - Created group: $group" >> $LOG_FILE
        fi
        usermod -aG $group $username
        echo "$(date) - Added $username to group: $group" >> $LOG_FILE
      done
    fi
Enter fullscreen mode Exit fullscreen mode

Running the Script

Before executing the script, ensure it has executable permissions. You can make it executable by granting the necessary permissions using:

chmod +x create_users.sh
Enter fullscreen mode Exit fullscreen mode

Run the Script with Root Privileges.

sudo ./create_users.sh
Enter fullscreen mode Exit fullscreen mode

After executing the script, it will display messages confirming the creation.

Conclusion

This bash script helps automate user creation and management making the process easier and saves time. This ensures all actions are logged and passwords stored securely.

To learn about this and more, check out HNG Internship and also check out HNG Hire for top talents.

Top comments (0)