My First Task In HNG Internship

I signup for an internship program named HNG. It is expected that the intern should have an intermediate to advance experience for any track they wish to participate in. For more information regarding the internship, your can follow this link https://h…


This content originally appeared on DEV Community and was authored by Ian alex

I signup for an internship program named HNG. It is expected that the intern should have an intermediate to advance experience for any track they wish to participate in. For more information regarding the internship, your can follow this link https://hng.tech/internship and applying for a job at HNG you can also checkout this link https://hng.tech/hire.

Task 1: We were tasked to write a script named create_user.sh for creating a user and adding the user to a group via reading from an input file.

#!/bin/bash
# Log file and password file
PASSWORD_FILE="/var/secure/user_passwords.txt"
LOG_FILE="/var/log/user_management.log"
# ensure to check if the number of argument provided is 1
# if !true exit running the entire codebase
if [ $# -ne 1 ]; then
    echo "Usage: $0 <input_textfile>" | sudo tee -a $LOG_FILE
    exit 1
fi

Considering the above code block;
#!/bin/bash the shebang declaration specifying that this file is a bash script.

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

the above block of code assigns the path /var/secure/user_passwords.txt to variable PASSWORD_FILE and path /var/log/user_management.log to variable LOG_FILE

if [ $# -ne 1 ]; then
    echo "This is how to run the script: $0 <input_textfile>" | sudo tee -a $LOG_FILE
    exit 1
fi

The above block of code checks if only argument is passed to the script.

  • $# -ne 1 checks if the number of argument passed is not equal to one and prints the output to the terminal and also log the data.
  • else if the condition doesn't hold true it exits the block of the code.
if [ ! -f "$input_textfile" ]; then
    echo "Error: The file $input_textfile does not exists" | sudo tee -a $LOG_FILE
    exit 1
fi
  • ! -f "$input_textfile this checks if an input file is not passed to the script it exits
sudo chown root:root $PASSWORD_FILE
sudo mkdir -p /var/secure
sudo touch $PASSWORD_FILE
sudo chmod 600 $PASSWORD_FILE
sudo touch $LOG_FILE
sudo chmod 640 $LOG_FILE
  • This Create necessary directories such as $LOG_FILE $PASSWORD_FILE and set permissions such as making the $PASSWORD_FILE have root administrative privilege and setting the permission to read and write privilege.
  • sudo chmod 640 $LOG_FILE this ensure that the user has a read and write privilege and the group has only read privilege.
generate_password() {
    < /dev/urandom tr -dc 'A-Za-z0-9!@#$%&*' | head -c 12
}
  • This function is responsible for generating random password

**Read File

while IFS=';' read -r user groups; do
    if [ -z "$user" ] || [ -z "$groups" ]; then
        echo "Skipping invalid line: $user;$groups" | sudo tee -a $LOG_FILE
        continue
    fi
  • Start a loop that reads a line from the $FILENAME, splits it into two parts separated by ; based on IFS.
  • read -r user groups Assign the first part to username and the remaining parts to groups.
  • -z "$user" -z "$groups" checks to see if the user and group name is empty.

** Creating users

if id -u "$user" >/dev/null 2>&1; then
        echo "This particular User $user exists" | sudo tee -a $LOG_FILE
    else
        sudo useradd -m -g "$user" -G "$user" "$user"
        if [ $? -eq 0 ]; then
            echo "User $user created" | sudo tee -a $LOG_FILE

            # Generating the random password for each user 
            password=$(generate_password)
            echo "$user,$password" | sudo tee -a $PASSWORD_FILE >/dev/null
            echo "$user:$password" | sudo chpasswd
            echo "User $user password is set" | sudo tee -a $LOG_FILE

            # Set appropriate permissions for the home directory
            sudo chmod 700 /home/$user
            sudo chown $user:$user /home/$user
            echo "Home directory for user $user set up with appropriate permissions" | sudo tee -a $LOG_FILE
        else
            echo "Failed to create user $user" | sudo tee -a $LOG_FILE
            continue
        fi
    fi
  • id -u "$user" >/dev/null 2>&1 this looks for the user id and suppress the standard output and error to /dev/null
  • sudo useradd -m -g "$user" -G "$user" "$user"
  • useradd: This is the command used to add a new user
  • -g "$user": Specifies the primary group for the new user. The group name is set to be the same as the username (denoted by $user).
  • -G "$user": Specifies additional groups for the new user. In this case, it adds the user to a group with the same name as the username.
  • "$user": This is the actual username of the new user being created.
  • [ $? -eq 0 ] this checks if the previous command successfully executed and 0 indicates success.
  • password=$(generate_password) calls the generate_password function and assigns the result to the password variable.
  • echo "$user,$password" | sudo tee -a $PASSWORD_FILE >/dev/null this suppresses the output due to the /dev/null
  • echo "$user:$password" | sudo chpasswd this allows the user to change password.
  • echo "User $user password is set" | sudo tee -a $LOG_FILE displays the output to the terminal. sudo chmod 700 /home/$user gives the user a full privileged. sudo chown $user:$user /home/$user gives the owner of the directory to the user. else if the condition doesn't hold true it print the output of failed user creation to the terminal.

** Adding Users to Group

IFS=',' read -r -a group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        if getent group "$group" >/dev/null 2>&1; then
            sudo usermod -aG "$group" "$user"
            echo "User $user added to existing group $group" | sudo tee -a $LOG_FILE
        else
            sudo groupadd "$group"
            sudo usermod -aG "$group" "$user"
            echo "Group $group created and user $user added to it" | sudo tee -a $LOG_FILE
        fi
    done
done < "$input_textfile"

-IFS=',' read -r -a group_array <<< "$groups"

  • IFS=',': Sets the Internal Field Separator to a comma. This means the read command will split the input string based on commas.
  • read -r -a group_array <<< "$groups" Reads the group variable, splits it by comma and stores the value to the group_array.
  • group=$(echo "$group" | xargs) this removes any leading whitespace in the group.
  • for group in "${group_array[@]}" this loops through the group_array array and stores each iteration to group.
  • if getent group "$group" >/dev/null 2>&1 if the group exists in the system; also suppress the standard output and error.
  • sudo usermod -aG "$group" "$user" adds users to the existing group
  • sudo groupadd "$group" this creates a new group.
  • sudo usermod -aG "$group" "$user" this adds user to the group
  • echo "Group $group created and user $user added to it" | sudo tee -a $LOG_FILE prints the output and log it into the log file.
  • done ends the for loop
  • done < "$input_textfile" ends the while loop that reads from the input file.
  • echo "User creation and group assignment created." | sudo tee -a $LOG_FILE outputting the finished the creation of users and group


This content originally appeared on DEV Community and was authored by Ian alex


Print Share Comment Cite Upload Translate Updates
APA

Ian alex | Sciencx (2024-07-03T00:40:39+00:00) My First Task In HNG Internship. Retrieved from https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/

MLA
" » My First Task In HNG Internship." Ian alex | Sciencx - Wednesday July 3, 2024, https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/
HARVARD
Ian alex | Sciencx Wednesday July 3, 2024 » My First Task In HNG Internship., viewed ,<https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/>
VANCOUVER
Ian alex | Sciencx - » My First Task In HNG Internship. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/
CHICAGO
" » My First Task In HNG Internship." Ian alex | Sciencx - Accessed . https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/
IEEE
" » My First Task In HNG Internship." Ian alex | Sciencx [Online]. Available: https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/. [Accessed: ]
rf:citation
» My First Task In HNG Internship | Ian alex | Sciencx | https://www.scien.cx/2024/07/03/my-first-task-in-hng-internship/ |

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.