User and groups creation automation in linux

Celestina - Jul 2 - - Dev Community

Hey there! Ever wondered how tech teams smoothly integrate new members into their systems? Scripting has become the unsung hero! Imagine effortlessly setting up user accounts, creating personalized groups, and ensuring security—all with a few lines of code. In this article, we'll explore how automation through scripting not only simplifies complex tasks but also minimizes errors and maximizes efficiency.

This scripting is part of a task assigned during the HNG Internship. The internship provides a premium at a stipend, exposing you to many more opportunities.

Tools Needed
Unix (Linux, macOS, WSL)
Editor (Vim, Vi, Nano, VSCode). I will be using Vim as the editor of choice; here is a link to learn more about Vim.

Scripting
First, create a file that will contain the script using touch create_users.sh. You can also create and open the file simultaneously using Vim:

touch create_users.sh
vim create_users.sh

Ensuring Root Privileges
At the start of the script, we need to ensure that only privileged users with root privileges can execute the script.

#!/bin/bash

# Check if running as root
if [[ $UID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi
Enter fullscreen mode Exit fullscreen mode

File Existence Check
The script checks if the user and group file exists. This is important for error handling and preventing repetition.

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

# Create the log and password files if they do not exist
touch $LOG_FILE
mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
Enter fullscreen mode Exit fullscreen mode

Logging Function
Next, we define a function to log activities into the log file.

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $1" >> $LOG_FILE
}
Enter fullscreen mode Exit fullscreen mode

Group Creation Function
We create a function to handle group creation. This ensures that groups are created only if they do not already exist.

# Function to create a group if it does not exist
create_group() {
    local group=$1

    if ! grep -q "^$group:" /etc/group; then
        groupadd "$group"
        if [ $? -eq 0 ]; then
            log "Created group: $group"
        else
            log "Failed to create group: $group"
            return 1
        fi
    fi
}
Enter fullscreen mode Exit fullscreen mode

User Creation Function
We create a function to handle user creation. This function will also manage group assignments and password generation.

# Function to create a user
create_user() {
    local user=$1         # Username passed as parameter
    local groups=$2       # Groups passed as parameter
    local password        # Variable to store generated password

    # Check if user already exists
    if id "$user" &>/dev/null; then
        echo "User $user already exists" | tee -a $LOG_FILE
        return 1
    fi

    # Create user's personal group if it doesn't exist
    create_group "$user"

    # Create any additional groups if they do not exist
    IFS=',' read -ra group_list <<< "$groups"
    for group in "${group_list[@]}"; do
        create_group "$group"
    done

    # Create the user with specified groups and assign a home directory
    useradd -m -s /bin/bash -g "$user" -G "$user,$groups" "$user" 2>>$LOG_FILE

    # Check if user creation was successful
    if [ $? -ne 0 ]; then
        echo "Failed to create user $user" | tee -a $LOG_FILE
        return 1
    fi

    # Generate a random password for the user
    password=$(openssl rand -base64 15)

    # Set user's password using chpasswd command
    echo "$user:$password" | chpasswd
    if [ $? -ne 0 ]; then
        echo "Failed to set password for user $user" | tee -a $LOG_FILE
        return 1
    fi

    # Store the password securely in the password file
    echo "$user,$password" >> $PASSWORD_FILE

    # Log user creation with assigned groups
    echo "Created user $user with groups $user,$groups" | tee -a $LOG_FILE

    # Set permissions for the user's home directory
    if [ ! -d "/home/$user" ]; then
        mkdir -p "/home/$user"
        chown -R "$user:$user" "/home/$user"
        chmod 700 "/home/$user"
        log "Created home directory for $user"
    fi
}
Enter fullscreen mode Exit fullscreen mode

Processing the User File
Next, the script reads the user file and processes each entry to create the users.

while IFS=';' read -r username groups; do
    username=$(echo $username | tr -d '[:space:]')   # Trim whitespace from username
    groups=$(echo $groups | tr -d '[:space:]')       # Trim whitespace from groups

    create_user "$username" "$groups"   # Call create_user function for each username and groups pair

done < "$USER_FILE"
Enter fullscreen mode Exit fullscreen mode

Testing
Make the script executable:

chmod +x create_users.sh
Now, to test the script, create a simple CSV file:

vim user_data.csv
Add the following content to user_data.csv:

Copy text into user_data.csv

light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
emeka;admin,dev
sarah;www-data
john;admin,sudo,dev
Check the log file to get the output:

sudo cat /var/log/user_management.log
And check the password file to see the generated passwords:

sudo cat /var/secure/user_passwords.txt

Outro
If you've gotten to this part and achieved the required results, then congratulations! If not, kindly go through the steps again.

Here is the link to my repo that you can use for reference or run directly after cloning.

cheers

.