DEV Community

Segun Moses
Segun Moses

Posted on

Automating Linux User Management with Bash Scripting

Managing user accounts on a Linux system can be daunting, especially in environments with frequent employee onboarding. As a DevOps engineer, familiar with operational SysOps functionalities, I often need a reliable, automated solution to streamline this process. This is where the create_users.sh Bash script comes into play, automating user creation and management based on input from a text file.

The Script’s Mission

The primary goal of create_users.sh is to automate the creation of user accounts on a Linux machine. Reading a specified text file containing usernames and associated groups, the script performs a series of operations to ensure each user is set up correctly with appropriate permissions and group memberships.

Step-by-Step Explanation

**

  1. Write your create_users.sh file (touch create_users.sh) **

Create a new script file named create_users.sh with the necessary permissions using the commands

I.

touch create_users.sh
Enter fullscreen mode Exit fullscreen mode

II.

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

**

  1. Check for Input File **

Before proceeding, the script verifies that you’ve provided an input file containing user and group information. This early check prevents errors and guides users on proper script usage. Create a text file sample user and group data sudo nano user_data.txt

#!/bin/bash

# Log file location
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

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

# Create log and password files
mkdir -p /var/secure
touch $LOGFILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

generate_random_password() {
    local length=${1:-10} # Default length is 10 if no argument is provided
    LC_ALL=C tr -dc 'A-Za-z0-9!?%+=' < /dev/urandom | head -c $length
}

# Function to create a user
create_user() {
  local username=$1
  local groups=$2

  if getent passwd "$username" > /dev/null; then
    echo "User $username already exists" | tee -a $LOGFILE
  else
    useradd -m $username
    echo "Created user $username" | tee -a $LOGFILE
  fi

  # Add user to specified groupsgroup
  groups_array=($(echo $groups | tr "," "\n"))

  for group in "${groups_array[@]}"; do
    if ! getent group "$group" >/dev/null; then
      groupadd "$group"
      echo "Created group $group" | tee -a $LOGFILE      
    fi
    usermod -aG "$group" "$username"
    echo "Added user $username to group $group" | tee -a $LOGFILE
  done

  # Set up home directory permissions
  chmod 700 /home/$username
  chown $username:$username /home/$username
  echo "Set up home directory for user $username" | tee -a $LOGFILE

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

# Read the input file and create users
while IFS=';' read -r username groups; do
  create_user "$username" "$groups"
done < "$1"

echo "User creation process completed." | tee -a $LOGFILE
Enter fullscreen mode Exit fullscreen mode

3. Define Variables

Key variables such as INPUT_FILE, LOG_FILE, and PASSWORD_FILE are defined to manage paths and filenames throughout the script. This enhances readability and makes maintenance easier.

4. Create Directories and Secure Password File

Ensuring security is paramount. The script creates necessary directories if they don’t exist and initializes a password file (/var/secure/user_passwords.csv) with stringent permissions (chmod 600). This ensures that only authorized users can access sensitive password information.

5. Define Functions

Modularity is key to maintainable scripting. The script defines two functions:

generate_password(): Utilizes OpenSSL to generate strong, random passwords for each user.
log_message(): Logs detailed actions and timestamps into LOG_FILE, facilitating troubleshooting and audit trails.

6. Read and Process Input File

The heart of the script lies in processing the input file:

It reads each line, compiles formatting, and parses usernames and associated groups.
For each user:
It checks if the user already exists to prevent duplication.
If not, it creates the user with their primary group and creates a secure home directory.
A random password is generated and securely stored in PASSWORD_FILE.
Additional specified groups are created if needed, and the user is added to these groups.

7. End of Script

Upon completion, the script logs a message indicating successful user creation and prompts users to review the LOG_FILE for detailed operations performed.

Image description

Important Decisions

Password Security: Emphasizing security, the script employs OpenSSL to generate robust passwords. Storing passwords in a file with restricted permissions (600) ensures compliance with security best practices.

Logging: Detailed logging (log_message()) aids in troubleshooting and provides an audit trail of script activities. This proves invaluable in diagnosing issues and maintaining accountability.

Error Handling: The script anticipates potential errors, such as missing input files or existing user accounts, and handles them gracefully to prevent disruptions.

Modular Functions: The script promotes code reuse and maintainability by encapsulating password generation and logging into functions.

Group Management: Dynamic group management ensures users are assigned to appropriate groups, enhancing system organization and access control.

**

Real-World Application

**

During my transformative journey with the HNG Internship, an immersive platform renowned for nurturing tech talents, I look towards encountering multifaceted challenges necessitating agile solutions. From creating seamless user provisioning amidst project expansions to fortifying data security protocols across distributed environments, the create_users.sh script emerged as a pivotal solution to overhead and task overload.

To explore how the HNG Internship empowers emerging tech professionals, check out their comprehensive programs such as HNG Internship and HNG Hire, known for industry excellence and transformative learning experiences.

Top comments (0)