Automating User and Group Management with Bash Scripting
Published: 2024-07-03 21:39:04

## **Introduction**

Managing user accounts and groups efficiently is crucial for system administrators to maintain security and streamline operations in Linux environments. This article explores the implementation and functionality of a Bash script named "create_users.sh", designed to automate user and group management tasks.

## **Script Overview**

The "create_users.sh" script is designed to read from an input file containing usernames and associated groups in a specific format (user;groups). It performs a series of operations to 
- create users, 
- manage groups, 
- assign permissions, and maintain security logs, all while adhering to best practices in system administration.

**## Block-by-Block Explanation**

**Block 1**: Root Privilege Check and Input Validation

```
# Check if the script is run with root privileges
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

# Check if the input file is provided as an argument
if [ $# -ne 1 ]; then
  echo "Please run this instead: $0 <name-of-text-file>"
  exit 1
fi
```
Purpose: Ensures the script is executed with root privileges to perform administrative tasks.

Functionality: Verifies if the input file (name-of-text-file) containing user and group data is provided as an argument.

Error Handling: Terminates execution with an error message if conditions are not met, guiding proper usage.

**Block 2**: File and Directory Initialisation

```
INPUT_FILE="$1"
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

# Ensure the log and password files exist and have the correct permissions
touch "$LOG_FILE"
chmod 644 "$LOG_FILE"
mkdir -p "$(dirname "$PASSWORD_FILE")"
touch "$PASSWORD_FILE"
chmod 600 "$PASSWORD_FILE"
chown root:root "$PASSWORD_FILE"

```
Purpose: Prepares necessary files and directories for logging and password storage.

Functionality:
- Initialises variables for input file path (INPUT_FILE), log file path (LOG_FILE), and password file path (PASSWORD_FILE).
- Creates or ensures existence of log file and password file with appropriate permissions (644 for logs, 600 for passwords).
- Sets ownership of the password file to root for enhanced security.
- Error Handling: The code snippet `mkdir -p "$(dirname "$PASSWORD_FILE")"` ensures that the path leading to the password file is created if not in existence before.

**Block 3**: Logging Function

```
# Function to log messages
log_message() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}
```

Purpose: Facilitates logging of script activities with timestamps.

Functionality:
- Defines log_message() function to prepend current timestamp to log messages.
- Appends (not overwrite) messages to the log file ($LOG_FILE) using tee -a for both real time display on the terminal and logging purposes into the file specified.

**Block 4**: User and Group Management Loop

```
# Read the input file and process each line
while IFS=";" read -r username groups; do
  # Trim any leading or trailing whitespace from username and groups
  username=$(echo "$username" | xargs)
  groups=$(echo "$groups" | xargs)

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

  # Create the primary group with the same name as the username
  if ! getent group "$username" > /dev/null; then
    groupadd "$username"
    log_message "Group $username created."
  else
    log_message "Group $username already exists."
  fi

  # Create the user with the primary group
  if ! id "$username" > /dev/null 2>&1; then
    useradd -m -g "$username" "$username"
    log_message "User $username created with primary group $username."
  else
    log_message "User $username already exists."
  fi

  # Add user to additional groups
  if [ -n "$groups" ]; then
    usermod -aG "$(echo $groups | tr ',' ' ')" "$username"
    log_message "User $username added to groups: $groups."
  fi

  # Generate a random password for the user
  password=$(openssl rand -base64 12)
  echo "$username:$password" | chpasswd
  log_message "Password set for user $username."

  # Store the password securely
  echo "$username,$password" >> "$PASSWORD_FILE"

done < "$INPUT_FILE"

log_message "User creation script completed successfully."

exit 0

```

Purpose: Implements core functionalities for user and group management.

Functionality:
- Input Parsing: Reads each line from the input file, extracting username and groups using semicolon (;) as delimiter.

- Group Management: Ensures creation of a primary group with the same name as the username.

- User Management: Creates users if they do not exist, assigns home directories (-m flag), and manages group memberships by adding users to additional groups as contained in the input file.

- Password Management: Generates random passwords securely using OpenSSL command "rand'and stores them in $PASSWORD_FILE.

- Logging: Logs each action with descriptive messages and timestamps by calling the earlier declared log_message() function.

## **Conclusion**

The create_users.sh script exemplifies efficient automation in Linux system administration, offering robust capabilities in user and group management. By following this structured approach, administrators can enhance operational efficiency, maintain security standards, and streamline user provisioning tasks across diverse IT environments.

As an initiative dedicated to nurturing talent in technology, the HNG Internship provides invaluable opportunities for aspiring developers and system administrators to enhance their skills. By leveraging tools like Bash scripting, professionals can streamline administrative tasks and contribute effectively to organizational objectives.

To learn more about the HNG Internship and its impact on tech enthusiasts worldwide, visit [HNG Internship](https://hng.tech/internship) and [HNG Hire](https://hng.tech/hire).