DEV Community

wanjiru murira
wanjiru murira

Posted on

Linux User Creation Bash Script

The purpose of this script is to read a text file containing an employee’s usernames and group names, where each line is formatted as user;groups.The script should create users and groups as specified, set up home directories with appropriate permissions and ownership and generate random passwords for the users.

The first line in this script is called a shebang which tells the OS which interpreter to use and in this case, the script will be interpreted and executed using Bash shell.

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

Some instances within the script require elevated permissions. To ensure that they are no errors when the script is executed, it is best to ensure that one is a root user when executing the script.

ROOT_UID=0     
if [ "$UID" -ne "$ROOT_UID" ]; then
    echo"***** You must be the root user to run this script!*****"
    exit
fi
Enter fullscreen mode Exit fullscreen mode

Key Functions
1. create_directories()

We need to first create two directories, /var/log/user_management.log and /var/secure/user_passwords.csv.The /var/log/user_management.log will be used to log all events that will be happening in our script and can be reviewed for troubleshooting.The /var/secure/user_passwords.csv will be used to store the created usernames and their passwords.This file is highly sensitive and should only be accessible to the owner.To achieve this, the permissions will be set to 700 on this file. chmod is used to set the appropriate permissions and chown is used to set ownership of the file.

log_dir="/var/log"
log_file="$log_dir/user_management.log"

secure_dir="/var/secure"
password_file="$secure_dir/user_passwords.csv"

# Function to create directories if they don't exist and assigning the necessary permission
create_directories() {
    # Create log directory if it doesn't exist
    if [ ! -d "$log_dir" ]; then
        sudo mkdir -p "$log_dir"
        sudo chmod 755 "$log_dir"
        sudo chown root:root "$log_dir"
    fi

    # Create secure directory if it doesn't exist
    if [ ! -d "$secure_dir" ]; then
        sudo mkdir -p "$secure_dir"
        sudo chmod 700 "$secure_dir"
        sudo chown root:root "$secure_dir"
    fi
}

Enter fullscreen mode Exit fullscreen mode

2. log()
The log() function records script activities with timestamps (date) in /var/log/user_management.log directory.

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

3. generate_password()
Before we can write a function to create a user, we first need to generate a random password for the newly created users.

generate_password() {
    # Set the desired length of the password
    local password_length=12 
    # Generate the password
    local password="$(openssl rand -base64 12 | tr -d '/+' | head -c $password_length)"  
    # Output the generated password
    echo "$password"  
}

Enter fullscreen mode Exit fullscreen mode

File Handling
The process_user_file() ensures the file exists and is readable before proceeding to create users and manage groups accordingly

 process_user_file() {
    local filename="$1"
    # Check if the file exists and is readable
    if [ ! -f "$filename" ]; then
        echo "****Error: File '$filename' not found or is not readable.****"
    log  "Error: File '$filename' not found or is not readable."
        return 1
    fi
Enter fullscreen mode Exit fullscreen mode

If the file is valid, a while loop will be used which will read the lines in the files and splits each line into username and groups , and then calls the function create_user with username and groups as arguments.

 while IFS=';' read -r username groups; do
        if [[ ! -z "$username" && ! -z "$groups" ]]; then
            create_user "$username" "$groups"
        else
            echo "****Invalid format in line: '$username;$groups'****" 
            log "Invalid format in line: '$username;$groups'"
        fi
    done < "$filename"
Enter fullscreen mode Exit fullscreen mode

User Management
Using the variables provided by the process_user_file function, we can create a user and generate a random password for them using generate_password function.
This command creates a user with a home directory /home/$"username.

sudo useradd -m -p "$(openssl passwd -6 "$password")" "$username"
# Making the user the owner of the directory
sudo chown "$username:$username" "/home/$username"
Enter fullscreen mode Exit fullscreen mode

By default when a user is created in most linux distribution, a group with the same name as the users username is created this group is usually the primary group of the user.However, to be on the safe side we can check if the group already exists and if not, we can create the group and add the user to the group then make the group the primary group of the user.

if ! grep -q "^$username:" /etc/group; then
           sudo groupadd "$username"
            #Adding the user to the group which is the primary group
            sudo usermod -aG group_name "$username"
            #change the primary group of a user
            sudo usermod -g "$username" "$username"
        fi
Enter fullscreen mode Exit fullscreen mode

In this last segment, we are going to add the users to the specified groups.
The variable groups is stored in an array known as group_list where we user the for function to iterate over each element in the group_list.

# Function to add users to specified groups
add_to_groups() {
    local username="$1"
    local groups="$2"
    IFS=',' read -ra group_list <<< "$groups"
    for group in "${group_list[@]}"; do
        if grep -q "^$group:" /etc/group; then
            sudo usermod -aG "$group" "$username"
            log "User '$username' added to group '$group' successfully."
            echo "****User '$username' added to group '$group' successfully.****"
        else
            log "Group '$group' does not exist. Skipping addition of user '$username'."
            echo "****Group '$group' does not exist. Skipping addition of user '$username'.****"
        fi
    done
}

Enter fullscreen mode Exit fullscreen mode

To make the script excutable, you need to use the chmod command in combination with the +x option

chmod +x path/directory/script.sh
Enter fullscreen mode Exit fullscreen mode

To execute the script, run:

./path/directory/script.sh text_file
Enter fullscreen mode Exit fullscreen mode

You can view the full script at Github.

This script was a task which was to be completed during my HNG internship. For those interested in practical learning and real-life scenarios, check out the HNG internship program. It's a great opportunity to gain hands-on experience! To maximize your internship experience, consider upgrading to their premium package at HNG Premium.

Top comments (0)