Linux User Creation Bash Script
Published: 2024-07-03 14:19:04

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
```

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
```
**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
}

```
**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"
}
```
**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"  
}

```
**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
```

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"
```
**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"
```
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
```
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
}

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

```
chmod +x path/directory/script.sh
```
To execute the script, run:

```
./path/directory/script.sh text_file
```

You can view the full script at [Github](https://github.com/wanjirumurira/Linux-User-Creation-Bash-Script.git).

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](https://hng.tech/internship). It's a great opportunity to gain hands-on experience! To maximize your internship experience, consider upgrading to their premium package at [HNG Premium](https://hng.tech/premium).