diff --git a/Challenges/Day_1/solution_day1_script.sh b/Challenges/Day_1/solution_day1_script.sh index 2b904ef..93853c6 100644 --- a/Challenges/Day_1/solution_day1_script.sh +++ b/Challenges/Day_1/solution_day1_script.sh @@ -1,31 +1,44 @@ #!/bin/bash +# Author: Yashraj Jaiswal +# Date: 01-08-2023 +# Description: #TWSBashBlazeChallenge Day - 1 -# First line of the script is the shebang which tells the system how to execute +# Task 1: Comments +# - Comments are lines in a script that are ignored by the interpreter and help us describe the script. -# Task 2: Echo -echo "Scripting is fun with @TWS" +# Task 2 : echo +echo "Today is Day 1 of #TWSBashBlazeChallenge an amazing bash scripting challenge" -# Task 3: Variables -variable1="Hello" -variable2="Bash" +# Task 3: Variables -# Task 4: Using Variables -greeting="$variable1, $variable2!" -echo "$greeting Welcome to the world of Bash scripting!" +# declaring and initializing variables +name = "Yashraj Jaiswal" +interests = "web dev | devops" -# Task 5: Using Built-in Variables -echo "My current bash path - $BASH" -echo "Bash version I am using - $BASH_VERSION" -echo "PID of bash I am running - $$" -echo "My home directory - $HOME" -echo "Where am I currently? - $PWD" -echo "My hostname - $HOSTNAME" +# Task 4: Using Variables -# Task 6: Wildcards -echo "Files with .txt extension in the current directory:" -ls *.txt +echo "Hello, my name is $name and I am interesed in $interests" +# Task 5: Using Built-in Variables +#use built-in variables from bash to print useful information +# print the host name +echo "Hostname: $HOSTNAME" + +# print the current user +echo "Current user: $USER" + +# print the current working directory +echo "Current directory: $PWD" + +# Task 6: Wildcards + +# using * wild card to search for files ending in .txt +ls -al *.txt + +# using ? wild card to search for files names ending with a single unknown character +ls -al file?.txt + +# using [] wild card to search for files that start with 'file' and have numbers 0-5 +ls -al 'file[0-5]'.txt -#Make sure to provide execution permission with the following command: -#chmod +x day1_script.sh diff --git a/Challenges/Day_2/backup_with_rotation.sh b/Challenges/Day_2/backup_with_rotation.sh index 2c5e56f..e75f389 100644 --- a/Challenges/Day_2/backup_with_rotation.sh +++ b/Challenges/Day_2/backup_with_rotation.sh @@ -1,41 +1,49 @@ #!/bin/bash - -# Function to display usage information and available options -function display_usage { - echo "Usage: $0 /path/to/source_directory" -} - -# Check if a valid directory path is provided as a command-line argument -if [ $# -eq 0 ] || [ ! -d "$1" ]; then - echo "Error: Please provide a valid directory path as a command-line argument." - display_usage +# Author: Yashraj Jaiswal +# Date: 01/08/2023 +# Description: TWSBashBlazeChallenge Day-2 +# Task 2: Directory Backup with Rotation + +# Validate input parameter for the directory to backup +if [ "$#" -ne 1 ]; +then + echo "Usage: $0 " + echo "Hint: enter the full path to the directory to backup" exit 1 fi -# Directory path of the source directory to be backed up -source_dir="$1" - -# Function to create a timestamped backup folder -function create_backup { - local timestamp=$(date '+%Y-%m-%d_%H-%M-%S') # Get the current timestamp - local backup_dir="${source_dir}/backup_${timestamp}" - - # Create the backup folder with the timestamped name - mkdir "$backup_dir" - echo "Backup created successfully: $backup_dir" -} - -# Function to perform the rotation and keep only the last 3 backups -function perform_rotation { - local backups=($(ls -t "${source_dir}/backup_"* 2>/dev/null)) # List existing backups sorted by timestamp - - # Check if there are more than 3 backups - if [ "${#backups[@]}" -gt 3 ]; then - local backups_to_remove="${backups[@]:3}" # Get backups beyond the last 3 - rm -rf "${backups_to_remove[@]}" # Remove the oldest backups - fi -} +path_to_dir="$1" +backup_dir="/var/backups" +max_backup_files=3 + +# Get the number of existing backup files in the backup directory +total_backup_files=$(find "$backup_dir" -type f -name "*.tgz" | wc -l) +echo +echo "Total backup files: $total_backup_files" + +# Check if more than the allowed number of backup files exist +if (( total_backup_files >= max_backup_files )); +then + echo + echo "More than $max_backup_files backup files detected" + # Sort the backup files by modification time and delete the oldest one + oldest_file=$(find "$backup_dir" -type f -name "*.tgz" | sort -r | tail -n 1) + echo "Deleting the oldest backup file - $oldest_file" + sudo rm -f "$oldest_file" +fi -# Main script logic -create_backup -perform_rotation +# Create a new tar file with timestamp in the filename +backup_file="backup_$(date +%d_%m_%Y_%H_%M_%S).tgz" +sudo tar -cvzf "$backup_dir/$backup_file" "$path_to_dir" > /dev/null 2>&1 + +# Check if the tar command executed successfully +if [[ $? -eq 0 ]]; +then + echo + echo "Backup created successfully" + echo "List of backups created in the past 3 days:" + sudo ls -lh "$backup_dir"/*.tgz | awk '{print "-",$NF, "\t(", $5, ")"}' +else + echo "Unable to create backup" +fi +echo \ No newline at end of file diff --git a/Challenges/Day_2/explorer.sh b/Challenges/Day_2/explorer.sh index be62ca1..db9c793 100644 --- a/Challenges/Day_2/explorer.sh +++ b/Challenges/Day_2/explorer.sh @@ -1,23 +1,31 @@ #!/bin/bash +#Author: Yashraj Jaiswal +# Date: 02/08/2023 +# Description: #TWSBashBlazeChallenge Day-2 +# Task 1: Interactive File and Directory Explorer -# Part 1: File and Directory Exploration -echo "Welcome to the Interactive File and Directory Explorer!" +# print a welcome message for the user +echo Welcome to the Interactive File and Directory Explorer! +# Format and display files and directories with their size in human readable format +echo "Files and Directories in current path - $PWD" +ls -lh | sed 1d | awk '{print "- ",$NF,"\t","(",$5,")"}' -while true; do - # List all files and directories in the current path - echo "Files and Directories in the Current Path:" - ls -lh - - # Part 2: Character Counting - read -p "Enter a line of text (Press Enter without text to exit): " input - - # Exit if the user enters an empty string - if [ -z "$input" ]; then - echo "Exiting the Interactive Explorer. Goodbye!" - break +# Infinite loop to continiously take user input +while true; +do + # prompt user to enter a text + echo -n "Enter a line of text (Press Enter without text to exit)" + read input + # use -z option to test for empty string + if [[ -z $input ]]; + then + echo Exiting the interactive explorer. Goodbye! + exit + else + # bash built-in string length + input_length=${#input} + # print the character count on screen + echo "Character count $input_length" fi - - # Calculate and print the character count for the input line - char_count=$(echo -n "$input" | wc -m) - echo "Character Count: $char_count" done + diff --git a/Challenges/Day_3/user_management.sh b/Challenges/Day_3/user_management.sh index 6f77f5d..5e5549a 100644 --- a/Challenges/Day_3/user_management.sh +++ b/Challenges/Day_3/user_management.sh @@ -1,94 +1,127 @@ #!/bin/bash +#Author: Yashraj Jaiswal +# Date: 03/08/2023 +# Description: #TWSBashBlazeChallenge Day-3 +# Task : User Account management -# Function to display usage information and available options -function display_usage { - echo "Usage: $0 [OPTIONS]" - echo "Options:" - echo " -c, --create Create a new user account." - echo " -d, --delete Delete an existing user account." - echo " -r, --reset Reset password for an existing user account." - echo " -l, --list List all user accounts on the system." - echo " -h, --help Display this help and exit." +check_user_exists(){ + id "$1" &> /dev/null + +} +check_group_exists(){ + getent group "$1" &> /dev/null } -# Function to create a new user account -function create_user { - read -p "Enter the new username: " username - - # Check if the username already exists - if id "$username" &>/dev/null; then - echo "Error: The username '$username' already exists. Please choose a different username." +create_user(){ + echo + local user_create_success + local passwd_create_success + read -p "Enter username: " username + check_user_exists "$username" + if (( $? == 0 )) + then + echo Error : $username user already exists else - # Prompt for password (Note: You might want to use 'read -s' to hide the password input) - read -p "Enter the password for $username: " password - - # Create the user account - useradd -m -p "$password" "$username" - echo "User account '$username' created successfully." + read -p "Enter password for user - $username : " password + if (( ${#password} <= 4 )) + then + echo Password should be atleast of 4 characters + else + check_group_exists "$username" + if (( $? == 0 )) + then + sudo useradd -g $username -m $username + else + sudo useradd -m $username + fi + user_create_success=$? + echo "$username:$password" | sudo chpasswd + passwd_create_success=$? + if (( user_create_success == 0 && passwd_create_success == 0 )) + then + echo User added successfully + else + sudo userdel -r $username > /dev/null 2>&1 + echo Unable to add user + fi + fi fi + echo } -# Function to delete an existing user account -function delete_user { - read -p "Enter the username to delete: " username - - # Check if the username exists - if id "$username" &>/dev/null; then - userdel -r "$username" # -r flag removes the user's home directory - echo "User account '$username' deleted successfully." +delete_user(){ + echo + read -p "Enter username : " username + check_user_exists "$username" + if (( $? == 0 )) + then + sudo userdel -r "$username" + if (( $? == 0 )) + then + echo User - "$username", deleted successfully + else + echo Error : unable to delete user + fi else - echo "Error: The username '$username' does not exist. Please enter a valid username." + echo Error : $username user doesnot exists fi + echo } -# Function to reset the password for an existing user account -function reset_password { - read -p "Enter the username to reset password: " username - - # Check if the username exists - if id "$username" &>/dev/null; then - # Prompt for password (Note: You might want to use 'read -s' to hide the password input) - read -p "Enter the new password for $username: " password - - # Set the new password - echo "$username:$password" | chpasswd - echo "Password for user '$username' reset successfully." +reset_user_passwd(){ + echo + read -p "Enter username to reset password : " username + check_user_exists "$username" + if (( $? == 1 )) + then + echo Error : $username user doesnot exists else - echo "Error: The username '$username' does not exist. Please enter a valid username." + read -p "Enter new password for $username : " password + if (( ${#password} <= 4 )) + then + echo Password should be atleast of 4 characters + else + echo "$username:$password" | sudo chpasswd + if (( $? == 0 )) + then + echo Password for user "$username" changed successfully + else + echo Error : Unable to change password for user "$username" + fi + fi fi + echo } -# Function to list all user accounts on the system -function list_users { - echo "User accounts on the system:" - cat /etc/passwd | awk -F: '{ print "- " $1 " (UID: " $3 ")" }' +list_users(){ + echo + echo "List of users on the system:" + sudo cat /etc/passwd | awk -F: '{print $1}' + echo } -# Check if no arguments are provided or if the -h or --help option is given -if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then - display_usage - exit 0 -fi +display_script_options(){ + echo + echo "Usage: $0 [OPTIONS]" + echo Options: + echo "-c, --create Create a new user account." + echo "-d, --delete Delete an existing user account." + echo "-r, --reset Reset password for an existing user account." + echo "-l, --list List all user accounts on the system." + echo "-h, --help Display this help and exit." + echo +} -# Command-line argument parsing -while [ $# -gt 0 ]; do - case "$1" in - -c|--create) - create_user - ;; - -d|--delete) - delete_user - ;; - -r|--reset) - reset_password - ;; - -l|--list) - list_users - ;; - *) - echo "Error: Invalid option '$1'. Use '--help' to see available options." - exit 1 - ;; +main(){ + case $1 in + "-c" | "--create") create_user ;; + "-d" | "--delete") delete_user;; + "-r" | "--reset") reset_user_passwd;; + "-l" | "--list") list_users;; + "-h" | "--help") display_script_options;; + *) display_script_options;; esac - shift -done +} + +main "$1" + diff --git a/Challenges/Day_4/Sol_monitor_process.sh b/Challenges/Day_4/Sol_monitor_process.sh deleted file mode 100644 index 2cd9bbf..0000000 --- a/Challenges/Day_4/Sol_monitor_process.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash - -# Function to check if the specified process is running -is_process_running() { - if pgrep -x "$1" >/dev/null; then - return 0 - else - return 1 - fi -} - -# Function to restart the process using systemctl -restart_process() { - local process_name="$1" - echo "Process $process_name is not running. Attempting to restart..." - - # Check if the user has the privilege to restart the process - if sudo systemctl restart "$process_name"; then - echo "Process $process_name restarted successfully." - else - echo "Failed to restart $process_name. Please check the process manually." - fi -} - -# Check if a process name is provided as an argument -if [ $# -eq 0 ]; then - echo "Usage: $0 " - exit 1 -fi - -process_name="$1" -max_attempts=3 -attempt=1 - -# Loop to check and restart the process -while [ $attempt -le $max_attempts ]; do - if is_process_running "$process_name"; then - echo "Process $process_name is running." - else - restart_process "$process_name" - fi - - attempt=$((attempt + 1)) - sleep 5 # Wait for 5 seconds before the next check -done - -echo "Maximum restart attempts reached. Please check the process manually." - diff --git a/Challenges/Day_4/Sol_monitoring_script.sh b/Challenges/Day_4/Sol_monitoring_script.sh deleted file mode 100644 index dbe41a0..0000000 --- a/Challenges/Day_4/Sol_monitoring_script.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash - -# Function to display system metrics (CPU, memory, disk space) -function view_system_metrics() { - echo "---- System Metrics ----" - # Fetch CPU usage using `top` command and extract the value using awk - cpu_usage=$(top -bn 1 | grep '%Cpu' | awk '{print $2}') - # Fetch memory usage using `free` command and extract the value using awk - mem_usage=$(free | grep Mem | awk '{printf("%.1f", $3/$2 * 100)}') - # Fetch disk space usage using `df` command and extract the value using awk - disk_usage=$(df -h / | tail -1 | awk '{print $5}') - - echo "CPU Usage: $cpu_usage% Mem Usage: $mem_usage% Disk Space: $disk_usage" -} - -# Function to monitor a specific service -function monitor_service() { - echo "---- Monitor a Specific Service ----" - read -p "Enter the name of the service to monitor: " service_name - - # Check if the service is running using `systemctl` command - if systemctl is-active --quiet $service_name; then - echo "$service_name is running." - else - echo "$service_name is not running." - read -p "Do you want to start $service_name? (Y/N): " choice - if [ "$choice" = "Y" ] || [ "$choice" = "y" ]; then - # Start the service using `systemctl` command - systemctl start $service_name - echo "$service_name started successfully." - fi - fi -} - -# Main loop for continuous monitoring -while true; do - echo "---- Monitoring Metrics Script ----" - echo "1. View System Metrics" - echo "2. Monitor a Specific Service" - echo "3. Exit" - - read -p "Enter your choice (1, 2, or 3): " choice - - case $choice in - 1) - view_system_metrics - ;; - 2) - monitor_service - ;; - 3) - echo "Exiting the script. Goodbye!" - exit 0 - ;; - *) - echo "Error: Invalid option. Please choose a valid option (1, 2, or 3)." - ;; - esac - - # Sleep for 5 seconds before displaying the menu again - sleep 5 -done diff --git a/Challenges/Day_4/monitor_metric.sh b/Challenges/Day_4/monitor_metric.sh new file mode 100644 index 0000000..9707673 --- /dev/null +++ b/Challenges/Day_4/monitor_metric.sh @@ -0,0 +1,98 @@ +#!/bin/bash +#Author: Yashraj Jaiswal +# Date: 03/08/2023 +# Description: #TWSBashBlazeChallenge Day-4 +# Task - part - 2 : Monitoring system metrics +# display metrics and monitor spcific process + +check_service_exists(){ + systemctl list-unit-files -q -all "$1.service" > /dev/null 2>&1 +} + +is_process_active() { + local process_status=$(systemctl is-active "$1" 2> /dev/null) + if [[ "$process_status" == "active" ]]; then + exit 0 + else + exit 1 + fi +} + +# Function to restart the process +restart_process() { + echo "Attempting to start process: $1" + sudo systemctl restart $1 + if $(is_process_active "$1"); then + echo "Process '$1' is running properly now." + else + echo "Unable to start $1 process." + fi + echo +} + +display_system_metrics(){ + local continue_script=1 + until [[ $continue_script -eq 0 ]] + do + echo "----- System metrics -----" + local cpu_usage=$(top -bn1 | grep '%Cpu' | awk '{print $2 + $4}') + local mem_usage=$(free | awk '/Mem/{print $3/$2 * 100.0}') + local disk_usage=$(df -h | awk '/\/dev\/root/{print $5}') + echo "CPU Usage : $cpu_usage%" + echo "Memory Usage : $mem_usage%" + echo "Disk Space : $disk_usage" + echo "----- System metrics -----" + echo "1. Print metrics again | 2. Go to main menu" + read -p "Enter your choice: " choice + + if [[ $choice -eq 1 ]]; then + continue_script=1 + else + continue_script=0 + fi + done +} + +monitor_service(){ + echo + echo "---------- Monitor a specific service ----------" + read -p "Enter the name of the service you want to monitor : " service_name + check_service_exists "$service_name" + if [ $? -eq 1 ]; + then + echo "Service for process - $service_name doesnot exists." + else + if $(is_process_active "$service_name"); then + echo "$service_name is running." + else + echo "$service_name process is not running" + read -p "Do you want to start $service_name (y/n) " choice + if [ "$choice" == "y" ]; then + restart_process "$service_name" + fi + fi + fi +} + +main() { + local continue_script=0 + while [[ $continue_script -eq 0 ]] + do + echo + echo "---------- Monitoring metrics script ----------" + echo "1. View system metrics." + echo "2. Monitor a specific service." + echo "3. Exit" + echo "---------- Monitoring metrics script ----------" + echo + read -p "Enter your choice: " choice + case $choice in + 1) display_system_metrics;; + 2) monitor_service;; + 3) continue_script=1 ;; + *) continue_script=1 ;; + esac + done +} + +main \ No newline at end of file diff --git a/Challenges/Day_4/monitor_pro.sh b/Challenges/Day_4/monitor_pro.sh new file mode 100644 index 0000000..d906120 --- /dev/null +++ b/Challenges/Day_4/monitor_pro.sh @@ -0,0 +1,67 @@ +#!/bin/bash +#Author: Yashraj Jaiswal +# Date: 03/08/2023 +# Description: #TWSBashBlazeChallenge Day-4 +# Task - part - 1 : Monitoring system process +# script start +# Define the name of the process you want to monitor +PROCESS_NAME="$1" +# Maximum number of restart attempts +MAX_RESTART_ATTEMPTS=3 + +# function to check if the given service exists or not +check_service_exists(){ + systemctl list-unit-files -q -all "$PROCESS_NAME.service" > /dev/null 2>&1 +} + +# Function to check if the process is running +is_process_active() { + local process_status=$(systemctl is-active $PROCESS_NAME 2> /dev/null) + if [[ "$process_status" == "active" ]]; then + exit 0 + else + exit 1 + fi +} + +# Function to restart the process +restart_process() { + echo + echo "Process '$PROCESS_NAME' is not running. Attempting to restart..." + # Loop to check and restart the process + for ((attempt=1; attempt<=$MAX_RESTART_ATTEMPTS; attempt++)); do + if $(is_process_active); then + echo "Process '$PROCESS_NAME' is running properly now." + break + else + if [ $attempt -lt $MAX_RESTART_ATTEMPTS ]; then + sudo systemctl restart $PROCESS_NAME + sleep 2 + else + echo "Maximum restart attempts reached. Please check the process '$PROCESS_NAME' manually." + exit 1 + fi + fi + done + echo +} + + +main(){ + echo + # check if the services exists for the given process name + check_service_exists + if [ $? -eq 1 ]; + then + echo "Service for process '$PROCESS_NAME' doesnot exists." + else + if $(is_process_active); then + echo "Process '$PROCESS_NAME' is running properly." + else + restart_process + fi + fi + echo +} + +main \ No newline at end of file diff --git a/Challenges/Day_5/log_analyzer.sh b/Challenges/Day_5/log_analyzer.sh index 70779dc..aec137b 100644 --- a/Challenges/Day_5/log_analyzer.sh +++ b/Challenges/Day_5/log_analyzer.sh @@ -1,56 +1,63 @@ #!/bin/bash - -# Check if the user provided the log file path as a command-line argument -if [ $# -ne 1 ]; then - echo "Usage: $0 " - exit 1 -fi - -# Get the log file path from the command-line argument -log_file="$1" - -# Check if the log file exists -if [ ! -f "$log_file" ]; then - echo "Error: Log file not found: $log_file" - exit 1 -fi - -# Step 1: Count the total number of lines in the log file -total_lines=$(wc -l < "$log_file") - -# Step 2: Count the number of error messages (identified by the keyword "ERROR" in this example) -error_count=$(grep -c -i "ERROR" "$log_file") - -# Step 3: Search for critical events (lines containing the keyword "CRITICAL") and store them in an array -mapfile -t critical_events < <(grep -n -i "CRITICAL" "$log_file") - -# Step 4: Identify the top 5 most common error messages and their occurrence count using associative arrays -declare -A error_messages -while IFS= read -r line; do - # Use awk to extract the error message (fields are space-separated) - error_msg=$(awk '{for (i=3; i<=NF; i++) printf $i " "; print ""}' <<< "$line") - ((error_messages["$error_msg"]++)) -done < <(grep -i "ERROR" "$log_file") - -# Sort the error messages by occurrence count (descending order) -sorted_error_messages=$(for key in "${!error_messages[@]}"; do - echo "${error_messages[$key]} $key" -done | sort -rn | head -n 5) - -# Step 5: Generate the summary report in a separate file -summary_report="log_summary_$(date +%Y-%m-%d).txt" -{ - echo "Date of analysis: $(date)" - echo "Log file: $log_file" - echo "Total lines processed: $total_lines" - echo "Total error count: $error_count" - echo -e "\nTop 5 error messages:" - echo "$sorted_error_messages" - echo -e "\nCritical events with line numbers:" - for event in "${critical_events[@]}"; do - echo "$event" - done -} > "$summary_report" - -echo "Summary report generated: $summary_report" - +#Author: Yashraj Jaiswal +# Date: 05/08/2023 +# Description: #TWSBashBlazeChallenge Day-5 +# Task : create a log analyzer script + +function error_count(){ + egrep -i -c "ERROR|faliure" $1 +} + +function critical_events(){ + filename="your_file.txt" + pattern="CRITICAL" + line_number=1 + while IFS= read -r line; do + if [[ $line == *"$pattern"* ]]; then + echo "Line $line_number: $line" + fi + ((line_number++)) + done < "$1" +} + +function top5_error_message(){ + egrep -i "ERROR|faliure" "$1" | sort | rev | cut -d ' ' -f 3- | rev | uniq -c | sort -r | head -5 +} + +function generate_summary(){ + echo "Date of analysis : $(date +"%D")" + echo "Log file name : $1" + echo "Total line processed : $(wc -l $1 | awk '{print $1}')" + echo "Total error count : $(error_count $1)" + echo + echo + echo "Top 5 error messages:" + echo + top5_error_message "$1" + echo + echo + echo "List of critical events with line number : " + echo + critical_events "$1" +} + +function main(){ + # check if the user has passed any file in command line + if (( $# == 0 )); then + echo "Info : this script analyzes a log file and creates a summary out of it." + echo "Usage : $0 path-to-file." + exit 1 + fi + # check if the given file is empty or not. + if [ ! -s "$1" ]; then + echo "$1 file is empty" + exit 1 + fi + local log_summary_file="log_summary_$(date +"%Y_%m_%d").txt" + touch "$log_summary_file" + generate_summary "$1" > "$log_summary_file" + sudo mv "./$log_summary_file" /var/log + echo "Summary report generated: /var/log/$log_summary_file" +} + +main "$1" \ No newline at end of file diff --git a/Challenges/Day_6/broken_myst/mystery.sh b/Challenges/Day_6/broken_myst/mystery.sh index dba59f3..676e12b 100644 --- a/Challenges/Day_6/broken_myst/mystery.sh +++ b/Challenges/Day_6/broken_myst/mystery.sh @@ -1,43 +1,28 @@ #!/bin/bash +# Date: 06/08/2023 +# Description: #TWSBashBlazeChallenge Day-6 +# Task, part -1 : Analyzing the Mysterious Function -# Welcome to the Mysterious Script Challenge! -# Your task is to unravel the mystery behind this script and understand what it does. -# Once you've deciphered its objective, your mission is to improve the script by adding comments and explanations for clarity. - -# DISCLAIMER: This script is purely fictional and does not perform any harmful actions. -# It's designed to challenge your scripting skills and creativity. - -# The Mysterious Function mysterious_function() { - local input_file="$1" - local output_file="$2" - - # + local input_file="$1" # Store the input file path + local output_file="$2" # Store the output file path + # Step 1: Apply a ROT13-like cipher to input_file and save the result in output_file tr 'A-Za-z' 'N-ZA-Mn-za-m' < "$input_file" > "$output_file" - - # + # Step 2: Reverse the text from output_file and save it in reversed_temp.txt rev "$output_file" > "reversed_temp.txt" - - # + # Step 3: Generate a random number between 1 and 10 random_number=$(( ( RANDOM % 10 ) + 1 )) - - # Mystery loop: + # Repeat the following block of operations random_number times for (( i=0; i<$random_number; i++ )); do - # + # Step 4: Reverse the text from reversed_temp.txt and save it in temp_rev.txt rev "reversed_temp.txt" > "temp_rev.txt" - - # + # Step 5: Apply the same ROT13-like cipher to temp_rev.txt and save it in temp_enc.txt tr 'A-Za-z' 'N-ZA-Mn-za-m' < "temp_rev.txt" > "temp_enc.txt" - - # + # Step 6: Replace reversed_temp.txt with temp_enc.txt mv "temp_enc.txt" "reversed_temp.txt" done - - # Clean up temporary files + # Clean up: Remove the temporary file temp_rev.txt rm "temp_rev.txt" - - # The mystery continues... - # The script will continue with more operations that you need to figure out! } # Main Script Execution @@ -48,8 +33,8 @@ if [ $# -ne 2 ]; then exit 1 fi -input_file="$1" -output_file="$2" +input_file="$1" # Store the input file path +output_file="$2" # Store the output file path # Check if the input file exists if [ ! -f "$input_file" ]; then @@ -61,4 +46,4 @@ fi mysterious_function "$input_file" "$output_file" # Display the mysterious output -echo "The mysterious process is complete. Check the '$output_file' for the result!" +echo "The mysterious process is complete. Check the '$output_file' for the result!" \ No newline at end of file diff --git a/Challenges/Day_6/broken_resto/restaurant_order.sh b/Challenges/Day_6/broken_resto/restaurant_order.sh index 2f64c3e..cba8561 100644 --- a/Challenges/Day_6/broken_resto/restaurant_order.sh +++ b/Challenges/Day_6/broken_resto/restaurant_order.sh @@ -1,57 +1,93 @@ #!/bin/bash +#Author: Yashraj Jaiswal +# Date: 05/08/2023 +# Description: #TWSBashBlazeChallenge Day-6 +# Task part - 2 : fix the restaurant ordering system script -# Function to read and display the menu from menu.txt file +# Declare associative arrays to store menu item values, ordered quantities, and menu items. +declare -A menu_item_value +declare -A item_quantity_ordered +declare -A menu_items + +# Function to read menu items and their values from a file and populate the associative arrays. +function populate_menu() { + local menu_file="./menu.txt" + local index=0 + while IFS=", " read -r menu_item menu_item_value; do + menu_items[$index]=$menu_item + menu_item_value[$menu_item]=$menu_item_value + ((index++)) + done < "$menu_file" +} + +# Function to display the menu items and their corresponding values. function display_menu() { - echo "Welcome to the Restaurant!" - echo "Menu:" - # TODO: Read the menu from menu.txt and display item numbers and prices - # Format: 1. Burger - ₹120 - # 2. Pizza - ₹250 - # 3. Salad - ₹180 - # ... + local index=1 + for key in "${menu_items[@]}"; do + echo -e "$index. $key \t- ₹ ${menu_item_value[$key]}" + ((index++)) + done +} + +# Function to take the customer's order for various menu items. +function take_order() { + local index=1 + echo "Menu items will appear one at a time. Enter the quantity when prompted." + echo "If you don't require an item, just press enter, and we will move to the next item." + + # take input for every item in the menu + for key in "${menu_items[@]}"; do + # take input from the customer until a numeric value is added + while true; do + read -p "$index. $key: " quantity + # if input is empty move to next item + if [[ -z "$quantity" ]]; then + break + # add to order only when input is a number + elif [[ $quantity =~ ^[0-9]+$ ]]; then + item_quantity_ordered["$key"]=$quantity + break + # for any input other than a number keep prompting the user for a numeric input + else + # Print an informative message to indicate the user that the input can only be a number. + echo "Invalid input, enter quantity in number. Or press enter if item not required." + continue + fi + done + ((index++)) + done } -# Function to calculate the total bill +# Function to calculate the total bill based on the ordered quantities and item values. function calculate_total_bill() { local total=0 - # TODO: Calculate the total bill based on the customer's order - # The order information will be stored in an array "order" - # The array format: order[] = - # Prices are available in the same format as the menu display - # Example: If the customer ordered 2 Burgers and 1 Salad, the array will be: - # order[1]=2, order[3]=1 - # The total bill should be the sum of (price * quantity) for each item in the order. - # Store the calculated total in the "total" variable. - echo "$total" + for key in "${menu_items[@]}"; do + total=$((total + menu_item_value[$key] * item_quantity_ordered[$key])) + done + echo $total } -# Function to handle invalid user input -function handle_invalid_input() { - echo "Invalid input! Please enter a valid item number and quantity." +# Main function to execute the restaurant ordering process. +function main(){ + echo Welcome to the bash blaze restaurant + read -p "What's your name please : " customer_name + echo "$customer_name, here is our fantastic menu:" + # Show the menu to the customer + display_menu + echo Ready to order!! + # Take the customer's order + take_order + echo "Enjoy your meal, $customer_name..." + echo + echo + sleep 2 + echo "Thank you, $customer_name, for dining at our Bash Blaze restaurant." + # Generate the bill and present it to the customer + echo "Your total bill is: ₹$(calculate_total_bill)" } -# Main script -display_menu - -# Ask for the customer's name -# TODO: Ask the customer for their name and store it in a variable "customer_name" - -# Ask for the order -echo "Please enter the item number and quantity (e.g., 1 2 for two Burgers):" -read -a input_order - -# Process the customer's order -declare -A order -for (( i=0; i<${#input_order[@]}; i+=2 )); do - item_number="${input_order[i]}" - quantity="${input_order[i+1]}" - # TODO: Add the item number and quantity to the "order" array -done - -# Calculate the total bill -total_bill=$(calculate_total_bill) - -# Display the total bill with a personalized thank-you message -# TODO: Display a thank-you message to the customer along with the total bill -# The message format: "Thank you, ! Your total bill is ₹." +# Populate the menu items and values from the file. +populate_menu +# Call the main function to start the ordering process. +main diff --git a/Challenges/Day_6/broken_search/recursive_search.sh b/Challenges/Day_6/broken_search/recursive_search.sh index 501af36..36f1958 100644 --- a/Challenges/Day_6/broken_search/recursive_search.sh +++ b/Challenges/Day_6/broken_search/recursive_search.sh @@ -1,14 +1,45 @@ #!/bin/bash +#Author: Yashraj Jaiswal +# Date: 05/08/2023 +# Description: #TWSBashBlazeChallenge Day-6 +# Task part -3 : fix the recursive search script if [ $# -ne 2 ]; then - echo "Usage: ./recursive_search.sh " - exit 1 + echo "Usage : ./recursive_search.sh " + exit 1 fi -search_directory=$1 -target_file=$2 +search_dir="$1" +target_file="$2" -# TODO: Implement the recursive search logic here +# Function to perform recursive search for the target file +function recursive_file_search { + local current_dir="$1" + + # Loop through the contents of the current directory + for file in "$current_dir"/*; do + if [ -d "$file" ]; then + # If the current item is a directory, call the recursive_file_search function to check within the sub directory + recursive_file_search "$file" + elif [ -f "$file" ] && [[ "$(basename "$file")" == "$target_file" ]]; then + # If the current item is a file and its name matches the target file, print a success message + # then print the absolute path of the file + echo "File found!!!" + echo "Absolute path of $target_file - $file" + exit 0 + fi + done +} +# Check if the provided directory exists +if [ ! -d "$search_dir" ]; then + echo "Error: Directory '$search_dir' not found." + exit 1 +fi + +# Start the recursive search by calling the recursive_file_search function with the provided search directory +recursive_file_search "$search_dir" + +# If the loop completes without finding the target file, display a "File not found" message and exit with an error echo "File not found: $target_file" exit 1 diff --git a/Challenges/Day_7/deploy_app.png b/Challenges/Day_7/deploy_app.png new file mode 100644 index 0000000..65e0509 Binary files /dev/null and b/Challenges/Day_7/deploy_app.png differ diff --git a/Challenges/Day_7/deploy_app.sh b/Challenges/Day_7/deploy_app.sh new file mode 100644 index 0000000..bb4b10b --- /dev/null +++ b/Challenges/Day_7/deploy_app.sh @@ -0,0 +1,57 @@ +#!/bin/bash +function validate_cmd_arg_input(){ + echo "Step 1. Validating given files." + + for file in "$@"; do + if [ ! -e "$file" ];then + echo "$file doesnot exists." + exit 1 + fi + if [ ! -s "$file" ]; then + echo "$file is empty." + exit 1 + fi + done + echo "> File validation successful." +} + +function populate_client_list() { + echo + echo "Step 2. Load client list data from $1 file into the script." + + local index=1 + while IFS=', ' read -r name ip || [[ -n "$name" ]]; do + if [[ -n "$name" ]]; then + echo "Read: name='$name', ip='$ip'" + client_name_list[$index]=$name + client_ip_list["$name"]=$ip + ((index++)) + fi + done < "$1" + + echo "> Done." +} + +function connect_and_execute(){ + ssh -o StrictHostKeyChecking=no -i ./ec2key "ubuntu@$1" "$2" +} + +function deploy_app(){ + for client_name in "${client_name_list[@]}";do + local client_ip="${client_ip_list[$client_name]}" + echo "Deploying app on $client_ip" + connect_and_execute "$client_ip" "cd node_docker && sudo docker-compose -f docker-compose.yaml -f docker-compose.prod.yaml up -d" + echo + done +} + +function main(){ + if [ $# -ne 2 ];then + echo "Usage: ./secure_transfer.sh client_list_file clint_auth_key" + else + validate_cmd_arg_input $@ + populate_client_list "$1" + deploy_app + fi +} +main "$1" "$2" diff --git a/Challenges/Day_7/project_running.png b/Challenges/Day_7/project_running.png new file mode 100644 index 0000000..0c02cae Binary files /dev/null and b/Challenges/Day_7/project_running.png differ diff --git a/Challenges/Day_7/remote_execute.sh b/Challenges/Day_7/remote_execute.sh new file mode 100644 index 0000000..4498812 --- /dev/null +++ b/Challenges/Day_7/remote_execute.sh @@ -0,0 +1,112 @@ +#!/bin/bash +declare -A client_name_list +declare -A client_ip_list + +function validate_cmd_arg_input(){ + echo + echo "Step 1. Validating $1 file." + # check if user has provided a file of clients to read from + if [ $# -eq 0 ]; then + # print usage information + echo "Info : This script prepares remote clients for remote connection throught the main server" + echo "Usage : $0 /path/to/client_ip_list file" + exit 1 + fi + # check if the client list file provided by the user exists or not + if [ ! -e "$1" ]; then + echo "> The client ip list file provided does not exists." + exit 1 + fi + # check if the client list file is empty or not + if [ ! -s "$1" ]; then + echo "> The client ip list file provided is empty , please check and execute again" + exit 1 + fi + + echo "> File validation successful." +} + + +function populate_client_list() { + echo + echo "Step 2. Load client list data from $1 file in the script." + + local index=1 + while IFS=', ' read -r name ip || [[ -n "$name" ]]; do + if [[ -n "$name" ]]; then + echo "Read: name='$name', ip='$ip'" + client_name_list[$index]=$name + client_ip_list["$name"]=$ip + ((index++)) + fi + done < "$1" + + echo "> Done." +} + +function connect_and_execute(){ + ssh -o StrictHostKeyChecking=no -i ./ec2key "ubuntu@$1" "$2" +} + +function install_packages(){ + echo "Step 3. Installing packages on all clients." + + for client_name in "${client_name_list[@]}";do + local client_ip="${client_ip_list[$client_name]}" + echo + echo "Checking for docker on $client_ip" + connect_and_execute "$client_ip" "which docker > /dev/null 2>&1" + docker_installed=$? + + if [ $docker_installed -eq 0 ];then + echo "Docker is already installed." + echo + else + echo + echo "Docker doesnot exists on $client_ip" + echo "Installing now..." + connect_and_execute "$client_ip" "sudo apt-get update && sudo apt install docker.io -y > /dev/null 2>&1" + if [ $? -eq 0 ];then + echo "Docker successfully installed on $client_ip" + else + echo "Unable to install docker." + fi + fi + + echo "Installing docker compose on $client_ip" + connect_and_execute "$client_ip" "sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose && sudo chmod +x /usr/local/bin/docker-compose > /dev/null 2>&1" + echo + echo "Checking for nginx on $client_ip" + + connect_and_execute "$client_ip" "which nginx > /dev/null 2>&1" + nginx_installed=$? + + if [ $nginx_installed -eq 0 ];then + echo "Nginx is already installed." + else + echo + echo "Nginx doesnot exists on $client_ip" + echo "Installing now..." + connect_and_execute "$client_ip" "sudo apt-get update && sudo apt install nginx -y > /dev/null 2>&1" + if [ $? -eq 0 ];then + echo "Nginx successfully installed on $client_ip" + else + echo "Unable to install nginx." + fi + fi + + done +} + +function main(){ + # validate user input + validate_cmd_arg_input "$1" + sleep 1 + # populate client list data from the given flile + populate_client_list "$1" + sleep 1 + # if ssh key doesnot exists create it + install_packages +} + +main "$1" \ No newline at end of file diff --git a/Challenges/Day_7/remote_execute_snip.png b/Challenges/Day_7/remote_execute_snip.png new file mode 100644 index 0000000..13ef4a1 Binary files /dev/null and b/Challenges/Day_7/remote_execute_snip.png differ diff --git a/Challenges/Day_7/secure_transfer.png b/Challenges/Day_7/secure_transfer.png new file mode 100644 index 0000000..6b2ff6d Binary files /dev/null and b/Challenges/Day_7/secure_transfer.png differ diff --git a/Challenges/Day_7/secure_transfer.sh b/Challenges/Day_7/secure_transfer.sh new file mode 100644 index 0000000..ed6d66c --- /dev/null +++ b/Challenges/Day_7/secure_transfer.sh @@ -0,0 +1,59 @@ +#!/bin/bash +declare -A client_name_list +declare -A client_ip_list + +function validate_cmd_arg_input(){ + echo "Step 1. Validating given files." + + for file in "$@"; do + if [ ! -e "$file" ];then + echo "$file doesnot exists." + exit 1 + fi + if [ ! -s "$file" ]; then + echo "$file is empty." + exit 1 + fi + done + echo "> File validation successful." +} + +function populate_client_list() { + echo + echo "Step 2. Load client list data from $1 file into the script." + + local index=1 + while IFS=', ' read -r name ip || [[ -n "$name" ]]; do + if [[ -n "$name" ]]; then + echo "Read: name='$name', ip='$ip'" + client_name_list[$index]=$name + client_ip_list["$name"]=$ip + ((index++)) + fi + done < "$1" + + echo "> Done." +} + +function connect_and_execute(){ + ssh -o StrictHostKeyChecking=no -i ./ec2key "ubuntu@$1" "$2" +} + +function transfer_file(){ + for client_name in "${client_name_list[@]}";do + local client_ip="${client_ip_list[$client_name]}" + echo "Transferring project file to $client_ip" + scp -o StrictHostKeyChecking=no -i "$1" -r node_docker "ubuntu@$client_ip:/home/ubuntu" > /dev/null 2>&1 + done +} + +function main(){ + if [ $# -ne 2 ];then + echo "Usage: ./secure_transfer.sh client_list_file clint_auth_key" + else + validate_cmd_arg_input $@ + populate_client_list "$1" + transfer_file "$2" + fi +} +main "$1" "$2" \ No newline at end of file