Automating User and Group Creation with Bash Scripts

As a SysOps engineer, one of your tasks might involve creating and managing user accounts on a Linux server. To streamline this process, you can automate the creation of users and their associated groups using a bash script. This type of script can be …


This content originally appeared on DEV Community and was authored by Blessing

As a SysOps engineer, one of your tasks might involve creating and managing user accounts on a Linux server. To streamline this process, you can automate the creation of users and their associated groups using a bash script. This type of script can be useful in large companies to automate the creation of user accounts and assigning groups, saving time and ensuring consistency, especially when onboarding multiple new employees.

The following guide walks you through a bash script called create_users.sh, which:

  1. Reads a text file containing usernames and groups.
  2. Creates users with home directories and random passwords.
  3. Creates groups and assigns users to them.
  4. Sets up home directories with appropriate permissions.
  5. Logs actions to /var/log/user_management.log.
  6. Stores passwords securely in /var/secure/user_passwords.csv.

Prerequisites:

Ensure you have the necessary permissions and tools:

  • Before running the script, ensure you have root user privileges because the script requires administrative privileges to create users, groups, and set permissions.
  • The script also uses the OpenSSL command-line tool to generate secure, random passwords for the new users. Ensure that OpenSSL is installed on your system.

The Script

create_users.sh script:

#!/bin/bash

# Create log file and secure password file with proper permissions
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Ensure the script is run as root
if [ "$(id -u)" -ne 0; then
    echo "This script must be run as root."
    exit 1
fi

# Ensure the log file exists
touch "$LOG_FILE"

# Setup password file
if [ ! -d "/var/secure" ]; then
    mkdir /var/secure
fi
if [ ! -f "$PASSWORD_FILE" ]; then
    touch "$PASSWORD_FILE"
    chmod 600 "$PASSWORD_FILE"
fi

# Check if the input file is provided
if [ -z "$1" ]; then
    echo "Usage: bash create_users.sh <name-of-text-file>"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: No input file provided." >> "$LOG_FILE"
    exit 1
fi

# Read the input file line by line
while IFS=';' read -r username groups; do
    # Remove whitespace
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)

    # Check if the user already exists
    if id "$username" &>/dev/null; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: User $username already exists." >> "$LOG_FILE"
        continue
    fi

    # Create the user with a home directory
    useradd -m -s /bin/bash "$username"
    if [ $? -ne 0 ]; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: Failed to create user $username." >> "$LOG_FILE"
        continue
    fi
    echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: User $username created." >> "$LOG_FILE"

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

    # Save the password to the secure password file
    echo "$username,$password" >> "$PASSWORD_FILE"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: Password for user $username generated and stored." >> "$LOG_FILE"

    # Create groups for the user
    IFS=',' read -ra group_list <<< "$groups"
    for group in "${group_list[@]}"; do
        group=$(echo "$group" | xargs)
        # Validate group name
        if ! grep -qE '^[a-z][-a-z0-9]*[$]' <<< "$group"; then
            echo "$(date '+%Y-%m-%d %H:%M:%S') - WARNING: '$group' is not a valid group name." >> "$LOG_FILE"
            continue
        fi
        # Check if the group already exists
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
            echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: Group $group created." >> "$LOG_FILE"
        fi
        # Add the user to the group
        usermod -a -G "$group" "$username"
    done

    # Set ownership and permissions for the home directory
    chown -R "$username:$username" "/home/$username"
    chmod 700 "/home/$username"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: Home directory for user $username set up with appropriate permissions." >> "$LOG_FILE"

done < "$1"

echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: User creation script completed." >> "$LOG_FILE"

exit 0

Creating the Employee List

create a text file (employees.txt) with the following format using any editor: e.g

john; marketing
emma; marketing
alex; sales
lisa; it
mike; it
sara; hr
chris; finance
linda; marketing
james; sales

Running the Script

  1. Upload the script and text file:
    Place create_users.sh and employees.txt in a directory on your Ubuntu VM (e.g., /opt/scripts).

  2. Set permissions and execute:

   chmod +x /opt/scripts/create_users.sh
   sudo /opt/scripts/create_users.sh /opt/scripts/employees.txt

Verifying Execution

After running the script, verify its success by checking:

  1. User creation:
   id john
  1. Group assignments:
   groups john
  1. Log file:
   cat /var/log/user_management.log
  1. Password storage:
   cat /var/secure/user_passwords.csv

By following these steps, you can automate user and group management efficiently.

This article is part of a requirement for stage 1 task in HNG11 Internship. For more detailed information, check out the HNG Internship and HNG Hire. These resources provide excellent learning opportunities and support for aspiring SREs and DevOps Engineers.


This content originally appeared on DEV Community and was authored by Blessing


Print Share Comment Cite Upload Translate Updates
APA

Blessing | Sciencx (2024-07-04T10:44:40+00:00) Automating User and Group Creation with Bash Scripts. Retrieved from https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/

MLA
" » Automating User and Group Creation with Bash Scripts." Blessing | Sciencx - Thursday July 4, 2024, https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/
HARVARD
Blessing | Sciencx Thursday July 4, 2024 » Automating User and Group Creation with Bash Scripts., viewed ,<https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/>
VANCOUVER
Blessing | Sciencx - » Automating User and Group Creation with Bash Scripts. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/
CHICAGO
" » Automating User and Group Creation with Bash Scripts." Blessing | Sciencx - Accessed . https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/
IEEE
" » Automating User and Group Creation with Bash Scripts." Blessing | Sciencx [Online]. Available: https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/. [Accessed: ]
rf:citation
» Automating User and Group Creation with Bash Scripts | Blessing | Sciencx | https://www.scien.cx/2024/07/04/automating-user-and-group-creation-with-bash-scripts/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.