diff --git a/Challenges/Day_1/Day_1_Basics_Solution.sh b/Challenges/Day_1/Day_1_Basics_Solution.sh new file mode 100755 index 00000000..bda93563 --- /dev/null +++ b/Challenges/Day_1/Day_1_Basics_Solution.sh @@ -0,0 +1,27 @@ +############################################################################################## +#!/bin/bash # +############################################################################################## +# Author : Gurudeo ray # +############################################################################################## +# # +# Usage : Created this script to full fill Day 1 Bashblaze challenge # +# # +############################################################################################## + +echo "Created this script to full fill Day 1 Bashblaze challenge" + +#Defining 2 integer variable and assigning them a value +num1=2 +num2=5 + +#Printing sum of num1 and num2 +echo "Sum of $num1 and $num2 = $( expr $num1 + $num2 )" + +#Built-in variables +echo $HOSTNAME +echo $BASH +echo $# +echo $HOME + +#finding file name in home directoy and it's subdirectory with .jpg extension +find /home -name "*.jpg" \ No newline at end of file diff --git a/Challenges/Day_1_Basics.md b/Challenges/Day_1/day1_basics.md similarity index 99% rename from Challenges/Day_1_Basics.md rename to Challenges/Day_1/day1_basics.md index 0d4a6e77..64f7543e 100644 --- a/Challenges/Day_1_Basics.md +++ b/Challenges/Day_1/day1_basics.md @@ -31,3 +31,4 @@ Create a single bash script that completes all the Tasks mentioned above. Add co To submit your entry, create a GitHub repository and commit your script to it. Good luck with Day 1 of the Bash Scripting Challenge! Tomorrow, the difficulty will increase as we move on to more advanced concepts. Happy scripting! + diff --git a/Challenges/Day_2/Day_2_Challenge.md b/Challenges/Day_2/Day_2_Challenge.md new file mode 100644 index 00000000..1cd723cb --- /dev/null +++ b/Challenges/Day_2/Day_2_Challenge.md @@ -0,0 +1,93 @@ +Day 2 Bash Scripting Challenge - Interactive File and Directory Explorer +Welcome to Day 2 of the Bash Scripting Challenge! In this challenge, you will create a bash script that serves as an interactive file and directory explorer. The script will allow you to explore the files and directories in the current path and provide a character counting feature for the user's input. + +Challenge Description +The script will have two main parts: + +Part 1: File and Directory Exploration +Upon execution without any command-line arguments, the script will display a welcome message and list all the files and directories in the current path. +For each file and directory, the script will print its name and size in human-readable format (e.g., KB, MB, GB). This information will be obtained using the ls command with appropriate options. +The list of files and directories will be displayed in a loop until the user decides to exit the explorer. +Part 2: Character Counting +After displaying the file and directory list, the script will prompt the user to enter a line of text. +The script will read the user's input until an empty string is entered (i.e., the user presses Enter without any text). +For each line of text entered by the user, the script will count the number of characters in that line. +The character count for each line entered by the user will be displayed. +Example Interaction +$ ./explorer.sh +Welcome to the Interactive File and Directory Explorer! + +Files and Directories in the Current Path: +- file1.txt (100 KB) +- dir1 (2 MB) +- script.sh (3 KB) +... + +Enter a line of text (Press Enter without text to exit): Hello, this is a sample line. +Character Count: 27 + +Enter a line of text (Press Enter without text to exit): Another line to count. +Character Count: 25 + +Enter a line of text (Press Enter without text to exit): +Exiting the Interactive Explorer. Goodbye! +Submission Instructions +Create a bash script named explorer.sh that implements the Interactive File and Directory Explorer as described in the challenge. +Add comments in the script to explain the purpose and logic of each part. +Submit your entry by pushing the script to your GitHub repository. +Congratulations! You've completed Day 2 of the Bash Scripting Challenge. The challenge focuses on Command-Line Argument Parsing and Loops to build an interactive script that explores files, directories, and performs character counting. Happy scripting and exploring! + + +================================================================================ + +Directory Backup with Rotation +This is another challenge for Day 2 of the Bash Scripting Challenge! In this challenge, you will create a bash script that performs a backup of a specified directory and implements a rotation mechanism to manage backups. + +Challenge Description +Your task is to create a bash script that takes a directory path as a command-line argument and performs a backup of the directory. The script should create timestamped backup folders and copy all the files from the specified directory into the backup folder. + +Additionally, the script should implement a rotation mechanism to keep only the last 3 backups. This means that if there are more than 3 backup folders, the oldest backup folders should be removed to ensure only the most recent backups are retained. + +The script will create a timestamped backup folder inside the specified directory and copy all the files into it. It will also check for existing backup folders and remove the oldest backups to keep only the last 3 backups. + +Example Usage +Assume the script is named backup_with_rotation.sh. Here's an example of how it will look, also assuming the script is executed with the following commands on different dates: + +First Execution (2023-07-30): +$ ./backup_with_rotation.sh /home/user/documents +Output: + +Backup created: /home/user/documents/backup_2023-07-30_12-30-45 +Backup created: /home/user/documents/backup_2023-07-30_15-20-10 +Backup created: /home/user/documents/backup_2023-07-30_18-40-55 +After this execution, the /home/user/documents directory will contain the following items: + +backup_2023-07-30_12-30-45 +backup_2023-07-30_15-20-10 +backup_2023-07-30_18-40-55 +file1.txt +file2.txt +... +Second Execution (2023-08-01): +$ ./backup_with_rotation.sh /home/user/documents +Output: + +Backup created: /home/user/documents/backup_2023-08-01_09-15-30 +After this execution, the /home/user/documents directory will contain the following items: + +backup_2023-07-30_15-20-10 +backup_2023-07-30_18-40-55 +backup_2023-08-01_09-15-30 +file1.txt +file2.txt +... +In this example, the script creates backup folders with timestamped names and retains only the last 3 backups while removing the older backups. + +Submission Instructions +Create a bash script named backup_with_rotation.sh that implements the Directory Backup with Rotation as described in the challenge. + +Add comments in the script to explain the purpose and logic of each part. + +Submit your entry by pushing the script to your GitHub repository. + +Congratulations on completing Day 2 of the Bash Scripting Challenge! The challenge focuses on creating a backup script with rotation capabilities to manage multiple backups efficiently. Happy scripting and backing up! \ No newline at end of file diff --git a/Challenges/Day_2/backup_with_rotation.sh b/Challenges/Day_2/backup_with_rotation.sh new file mode 100755 index 00000000..0614a6cc --- /dev/null +++ b/Challenges/Day_2/backup_with_rotation.sh @@ -0,0 +1,59 @@ +############################################################################################## +#!/bin/bash # +############################################################################################## +# Author : Gurudeo ray # +############################################################################################## +# # +# About : Developed a shell script to backup resources, present in the directory provided # +# by a user as a input. # +# # +# # +############################################################################################## +# # +# Execution : ./ # +# # +# Example : ./backup_with_rotation.sh /home/guru/Documents/ # +# # +############################################################################################## + +# Taking directory input from user +backup_input_dir=$1 + +# Latest timestamp +time_stamp="$(date +'%Y-%m-%d_%H-%M-%S')" + +# Locatin to store all the backups +backup_storage_location=$backup_input_dir"/backup_"$time_stamp + +# Backup file name with latest timestamp +backup_file_name=backup_$time_stamp"".tar.gz + +# Creating backup storage location (storage directory) +mkdir -p $backup_storage_location + +# Taking backup and storing at the backup storage location +tar -cvf ${backup_storage_location}/${backup_file_name} ${backup_input_dir} 2>/dev/null 1>/dev/null +if [ $? -eq 0 ]; then + echo "Backup created: $backup_storage_location" +else + echo "Please enter valid directory name." +fi + +# Steps to keep latest 3 backups and delete old backups +for backup_list_item in $(ls -t $backup_input_dir | tail -n +4 | grep backup) +do + rm -r $backup_input_dir/$backup_list_item +done + + + +# Solution 1 (If we have more thank 1 extra backup except latest 3) +#solution 2 (if we have only one extra backup except latest 3) +# rm -r $backup_input_dir/$(ls -t $backup_input_dir | awk 'NR>3' | grep backup) + +#solution 3 (if we have only one extra backup except latest 3) +# rm -r $backup_input_dir/$(ls -t $backup_input_dir | tail -n +4 | grep backup) + + +#Dont forget to Give your script executable permission +#chmod +x backup_with_rotation.sh \ No newline at end of file diff --git a/Challenges/Day_2/explorer.sh b/Challenges/Day_2/explorer.sh new file mode 100755 index 00000000..779a0351 --- /dev/null +++ b/Challenges/Day_2/explorer.sh @@ -0,0 +1,32 @@ +############################################################################################## +#!/bin/bash # +############################################################################################## +# Author : Gurudeo ray # +############################################################################################## +# # +# About : Developed a script to full fill Day 2 Bashblaze challenge (Interactive File and # +# Directory Explorer) # +# # +############################################################################################## + +echo "Welcome to Day2 chalenge" + +#Printing all the file and directroies with their size in human redable format +echo "Files and directories in current path: " +ls -lh | awk -F " " '{ print $9 " ("$5")"}' + +isCondition=true + +#Creating interactive while loop to count characters provided by user as a input +while( $isCondition ); do + count=0 + read -p "Enter a line or characters (Press enter without any input to exit): " inputstring + if [[ $inputstring != "" ]];then + for(( i=0; i<${#inputstring}; i++ )); do + $(( count++ )) 2>/dev/null + done + echo "Character count : $count" + else + exit; + fi +done \ No newline at end of file diff --git a/Challenges/Day_3/day_3_usermgm.md b/Challenges/Day_3/day_3_usermgm.md new file mode 100644 index 00000000..8af9400c --- /dev/null +++ b/Challenges/Day_3/day_3_usermgm.md @@ -0,0 +1,57 @@ +## Challenge: User Account Management + +In this challenge, you will create a bash script that provides options for managing user accounts on the system. The script should allow users to perform various user account-related tasks based on command-line arguments. + +### Part 1: Account Creation + +1. Implement an option `-c` or `--create` that allows the script to create a new user account. The script should prompt the user to enter the new username and password. + +2. Ensure that the script checks whether the username is available before creating the account. If the username already exists, display an appropriate message and exit gracefully. + +3. After creating the account, display a success message with the newly created username. + +### Part 2: Account Deletion + +1. Implement an option `-d` or `--delete` that allows the script to delete an existing user account. The script should prompt the user to enter the username of the account to be deleted. + +2. Ensure that the script checks whether the username exists before attempting to delete the account. If the username does not exist, display an appropriate message and exit gracefully. + +3. After successfully deleting the account, display a confirmation message with the deleted username. + +### Part 3: Password Reset + +1. Implement an option `-r` or `--reset` that allows the script to reset the password of an existing user account. The script should prompt the user to enter the username and the new password. + +2. Ensure that the script checks whether the username exists before attempting to reset the password. If the username does not exist, display an appropriate message and exit gracefully. + +3. After resetting the password, display a success message with the username and the updated password. + +### Part 4: List User Accounts + +1. Implement an option `-l` or `--list` that allows the script to list all user accounts on the system. The script should display the usernames and their corresponding user IDs (UID). + +### Part 5: Help and Usage Information + +1. Implement an option `-h` or `--help` that displays usage information and the available command-line options for the script. + +### Bonus Points (Optional) + +If you want to challenge yourself further, you can add additional features to the script, such as: + +- Displaying more detailed information about user accounts (e.g., home directory, shell, etc.). +- Allowing the modification of user account properties (e.g., username, user ID, etc.). + +Remember to handle errors gracefully, provide appropriate user prompts, and add comments to explain the logic and purpose of each part of the script. + +## [Example Interaction: User Account Management Script](./example_interaction_with_usr_acc_mgmt.md) + + +## Submission Instructions + +Create a bash script named `user_management.sh` that implements the User Account Management as described in the challenge. + +Add comments in the script to explain the purpose and logic of each part. + +Submit your entry by pushing the script to your GitHub repository. + +Good luck with the User Account Management challenge! This challenge will test your ability to interact with user input, manage user accounts, and perform administrative tasks using bash scripting. Happy scripting and managing user accounts! diff --git a/Challenges/Day_3/example_interaction_with_usr_acc_mgmt.md b/Challenges/Day_3/example_interaction_with_usr_acc_mgmt.md new file mode 100644 index 00000000..0af35530 --- /dev/null +++ b/Challenges/Day_3/example_interaction_with_usr_acc_mgmt.md @@ -0,0 +1,45 @@ +# Here's an example how the interaction with the User Account Management script might look: + +> Assume the script is named user_management.sh. Let's go through different scenarios: + +![1](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/653bc7fb-ac50-4089-87fa-a6c3f616bc48) + + +### Scenario 1: Create a New User + +![2](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/b472a087-ae23-4d7b-bf4f-95ceca45f6e4) + + +### Scenario 2: Create a User with an Existing Username + +![3](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/fc664ca3-6c81-4370-b968-f66a07adf9af) + + +### Scenario 3: Delete a User Account + +![4](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/10fce4ff-894a-4385-8a17-dbf8991fba8c) + + +### Scenario 4: Delete a Non-Existing User Account + +![5](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/55d1c5ea-6ddb-4b81-9e4c-579b34961a0a) + + +### Scenario 5: Reset Password + +![6](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/d2177cbe-3896-40d8-b5ad-3d7b77cb4411) + + +### Scenario 6: List All User Accounts + +![7](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/4fc84ea5-ca2d-4438-ad7f-a47980edb3f9) + + +### Scenario 7: Help and Usage Information + +![8](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/7818c35c-29b6-44d4-ae63-c12918bdc806) + + +Please note that the actual output might differ based on your implementation of the script. Also, ensure that you handle different edge cases and error scenarios gracefully to make the script user-friendly and robust. + +This Markdown file demonstrates the interaction with the User Account Management script, showcasing various scenarios and expected outputs. The examples provide a clear understanding of how the script works and how users can interact with it. diff --git a/Challenges/Day_3/modify_user.sh b/Challenges/Day_3/modify_user.sh new file mode 100755 index 00000000..5dccb3ba --- /dev/null +++ b/Challenges/Day_3/modify_user.sh @@ -0,0 +1,84 @@ +#!/bin/bash + +#Menu option to modifu users +echo '' +echo '' +echo "Modify user menu: " +echo '' +echo "1. Add a user to a new group without chaging default group." +echo "2. Update a user's default group." +echo "3. Unlock a user." +echo "4. Lock a user." +echo "5. Update a user's password." +echo "6. Exit" +echo -n "Enter a menu choice [1 to 6]: " + +while : +do +read choice +case $choice in + 1) read -p "Please enter a group name: " groupupdate + read -p "Please enter username to add in group: " username + if [[ $groupupdate != '' && $username != '' ]]; then + usermod -G $groupupdate $username 2>/dev/null + if [[ $? -eq 0 ]]; then + echo "$username has been added to $groupupdate group." + else + echo "Please enter valid username or group name." + fi + else + echo "Please enter valid username or groupname." + fi;; + + 2) read -p "Please enter a group name: " groupupdate + read -p "Please enter username to add in group: " username + if [[ $groupupdate != '' && $username != '' ]]; then + usermod -g $groupupdate $username 2>/dev/null + if [[ $? -eq 0 ]]; then + echo "Default usergroup has been changed of $username" + else + echo "Please enter valid username or password." + fi + else + echo "Please enter valid username or groupname." + fi;; + + 3) read -p "Enter a username to unlock: " unlockuser + if [[ $unlockuser != '' ]]; then + usermod -U $unlockuser + if [[ $? -eq 0 ]]; then + echo "$unlockuser unlocked successfully." + else + echo "Please enter a valid username." + fi + else + echo "Please enter valid username." + fi;; + 4) read -p "Enter a username to lock: " lockuser + if [[ $lockuser != '' ]]; then + usermod -L $lockuser + if [[ $? -eq 0 ]]; then + echo "$lockuser locked successfully." + else + echo "Please enter a valid username." + fi + else + echo "Please enter valid username." + fi;; + + 5) read -p "Enter a username: " passupdateuser + if [[ $passupdateuser != '' ]]; then + passwd $passupdateuser + if [[ $? -eq 0 ]]; then + echo "Password updated successfully for $passupdateuser" + else + echo "Please enter correct username or password." + fi + else + echo "Please enter correct username or password." + fi;; + 6) exit;; + *) echo "Please enter a valid menu choice." +esac +echo -n "Enter a menu choice in [1 to 6]: " +done diff --git a/Challenges/Day_3/user_management.sh b/Challenges/Day_3/user_management.sh new file mode 100755 index 00000000..a7c4a678 --- /dev/null +++ b/Challenges/Day_3/user_management.sh @@ -0,0 +1,153 @@ +#!/bin/bash +######################################################################################################################### +# Version : 1.0 # +######################################################################################################################### +# # +# Author : Gurudeo ray # +# # +######################################################################################################################### +# # +# Description : We can perform user related operations using this script. # +# # +# Example : foldername<01> <90> # +# # +######################################################################################################################### + +#Creating menu with options +echo "Select your option" +echo "1. List out all groups name" +echo "2. List out all the users name" +echo "3. Add or delete a group" +echo "4. Add a user" +echo "5. Modify a user" +echo "6. Delete a user" +echo "7. Exit from menu" +echo '' +echo '' +echo -n "Enter your menu choice [1 to 7]: " + +# Running a forever loop using while statement +# This loop will run until select the exit option. +# User will be asked to select option again and again +while : +do + +default=y +isvalue=true +RED="\e[31m" +BLUE="\e[34m" +ENDCOLOR="\e[0m" + +#Reading choice +read choice + +#Case statement is used to compare one value with multiple cases and based on choice it switch to option +case $choice in +1) echo "List of group" + cat /etc/group | awk -F':' '{ print $1 }' + +2) echo "List of users" + cat /etc/passwd | awk -F':' '{ print $1 }';; + + ################### Group add or delete section #################################################### +3) read -p "Do you want to add a group (y -> to add user & n -> to delete user): " isgroup + if [[ $isgroup == 'y' || $isgroup == 'Y' || $isgroup == 'yes' || $isgroup == 'YES' || $isgroup == '' ]] + then + while ($isvalue) + do + read -p "Please enter your group name: " groupname + if [[ $groupname == '' ]] + then + echo -e "$RED Please enter valid group name.$ENDCOLOR" + else + groupadd $groupname 2> /dev/null + if [ $? -eq 0 ]; then + echo $groupname" has been added successfully." + isvalue=false + else + echo -e "$RED Please enter a valid username. $ENDCOLOR" + fi + fi + done + fi + if [[ $isgroup == 'n' || $isgroup == 'N' || $isgroup == 'no' || $isgroup == 'NO' ]] + then + while ($isvalue); do + read -p "Please enter a groupname to be deleted: " deletegroup + if [[ $deletegroup == '' ]] + then + echo -e "$RED Please enter a valid group name.$ENDCOLOR" + else + groupdel $deletegroup 2> /dev/null + if [ $? -eq 0 ]; then + echo $deletegroup" has been deleted successfully." + isvalue=false + else + echo -e "$RED $deletegroup does not exist ! Please enter valid groupname.$ENDCOLOR" + fi + fi + done + fi;; + ################### End of Group add or delete section #################################################### + + ################### Add user section ###################################################################### +4) #Enter user details + echo -e "$BLUE Enter all the user details $ENDCOLOR" + istrue=true + + while($istrue); do + + read -p "Enter a username: " username + read -p "Enter a group name (Optional): " group + read -p "Enter y or Y if you want to add HOME directory (Optional): " ishomedirectory + + if [[ $username != '' ]]; then + if [[ $group != '' && $ishomedirectory != '' ]]; then + useradd -g $group -m -d /home/$username -s /bin/bash $username 2>/dev/null + passwd $username + echo "$username addedd successfully." + id $username + istrue=false + elif [[ $group != '' ]]; then + useradd -g $group -s /bin/bash $username 2>/dev/null + passwd $username + echo "$username addedd successfully." + id $username + istrue=false + else + useradd -m -d /home/$username -s /bin/bash $username 2>/dev/null + passwd $username + echo "$username addedd successfully." + id $username + istrue=false + fi + else + echo -e "$RED Username or password missing $ENDCOLOR" + fi + done;; + ################### End Of Add user section ############################################################## + +5) bash /home/guru/guru/90DaysOfDevOpsChallenge/day05/modify_user.sh + ;; +6) read -p "Enter a username to be deleted: " deleteuser + if [[ $deleteuser != '' ]]; then + userdel -r $deleteuser 2>/dev/null + if [[ $? -eq 0 ]]; then + echo "$deleteuser delete successfuly." + else + echo "Please enter valid user to be deleted." + fi + else + echo "Please enter valid user to be deleted." + fi;; +7) exit;; + +*) echo "Invalid option";; + +esac + echo '' + echo '' + echo -n "Enter your menu choice [1 to 7] : " +done + + diff --git a/Challenges/Day_4/Part_1_monitor_pro.md b/Challenges/Day_4/Part_1_monitor_pro.md new file mode 100644 index 00000000..7f80f8b5 --- /dev/null +++ b/Challenges/Day_4/Part_1_monitor_pro.md @@ -0,0 +1,59 @@ +# BashBlaze Scripting Challenge - Day 4 + +Welcome to the Bash Scripting Challenge - Day 4! This challenge is designed to test your Bash scripting skills and problem-solving abilities in the context of process monitoring and management. + +## Scenario + +You are tasked with writing a Bash script that efficiently monitors a specific process on a Linux system. The script's primary goal is to ensure the process is always running, and if it unexpectedly stops, it should be restarted automatically. + +## Task + +1. **Process Selection:** + + - The script should accept a command-line argument to specify the target process to monitor. For example: `./monitor_process.sh `. + +2. **Process Existence Check:** + + - Implement a function that checks if the specified process is currently running on the system. + - If the process is running, print a message indicating its presence. + +3. **Restarting the Process:** + + - If the process is not running, implement a function that attempts to restart the process automatically. + - Print a message indicating the attempt to restart the process. + - Ensure the script does not enter an infinite loop while restarting the process. Limit the number of restart attempts. + +4. **Automation:** + + - Provide instructions on how to schedule the script to run at regular intervals using a cron job or any other appropriate scheduling method. + +5. **Documentation:** + + - Include clear and concise comments in the script to explain its logic and functionality. + - Write a separate document describing the purpose of the script, how to use it, and any specific considerations. + +6. **Bonus:** + - Implement a notification mechanism (e.g., email, Slack message) to alert administrators if the process requires manual intervention after a certain number of restart attempts. + +Remember to test your script thoroughly on a test system before deploying it to a production environment. Ensure it does not interfere with critical processes or cause any unintended side effects. Consider edge cases and potential race conditions during process monitoring and restarting. + +## Example Interaction + +Check the [example_interaction.md](./usr_example_interaction.md) +file to see a sample interaction with the script, demonstrating its usage and behavior. + +## Submission Guidelines + +1. Fork this repository to your GitHub account. +2. Implement the Bash script according to the provided scenario and tasks. +3. Create a new branch in your forked repository for your changes. +4. Commit your changes with meaningful commit messages. +5. Push your changes to your forked repository. +6. Create a pull request from your branch to the original repository. + +## Notes + +- You can customize the script, add more features, or enhance the error handling as you see fit. +- If you encounter any issues or have questions, feel free to open an issue in this repository. + +Happy scripting and good luck with the challenge! diff --git a/Challenges/Day_4/Part_2_Monitoring_Metrics.md b/Challenges/Day_4/Part_2_Monitoring_Metrics.md new file mode 100644 index 00000000..13e26295 --- /dev/null +++ b/Challenges/Day_4/Part_2_Monitoring_Metrics.md @@ -0,0 +1,43 @@ +# Monitoring Metrics Script with Sleep Mechanism + +## Challenge Description + +This project aims to create a Bash script that monitors system metrics like CPU usage, memory usage, and disk space usage. The script will provide a user-friendly interface, allow continuous monitoring with a specified sleep interval, and extend its capabilities to monitor specific services like Nginx. + +## Tasks + +### Task 1: Implementing Basic Metrics Monitoring + +Write a Bash script that monitors the CPU usage, memory usage, and disk space usage of the system. The script should display these metrics in a clear and organized manner, allowing users to interpret the data easily. The script should use the top, free, and df commands to fetch the metrics. + +### Task 2: User-Friendly Interface + +Enhance the script by providing a user-friendly interface that allows users to interact with the script through the terminal. Display a simple menu with options to view the metrics and an option to exit the script. + +### Task 3: Continuous Monitoring with Sleep + +Introduce a loop in the script to allow continuous monitoring until the user chooses to exit. After displaying the metrics, add a "sleep" mechanism to pause the monitoring for a specified interval before displaying the metrics again. Allow the user to specify the sleep interval. + +### Task 4: Monitoring a Specific Service (e.g., Nginx) + +Extend the script to monitor a specific service like Nginx. Check if the service is running and display its status. If it is not running, provide an option for the user to start the service. Use the systemctl or appropriate command to check and control the service. + +### Task 5: Allow User to Choose a Different Service + +Modify the script to give the user the option to monitor a different service of their choice. Prompt the user to enter the name of the service they want to monitor, and display its status accordingly. + +### Task 6: Error Handling + +Implement error handling in the script to handle scenarios where commands fail or inputs are invalid. Display meaningful error messages to guide users on what went wrong and how to fix it. + +### Task 7: Documentation + +Add comments within the script to explain the purpose of each function, variable, and section of the code. Provide a clear and concise README file explaining how to use the script, the available options, and the purpose of the script. + +Remember, the main goal of this challenge is to utilize various monitoring commands, implement a user-friendly interface, and create a script that is easy to understand and use. + +Feel free to explore and research relevant commands and syntax while completing the tasks.Enjoy monitoring your system metrics effortlessly + +## You can also check out the [interactive monitoring Metrics script repository](./usr_interaction_with_metrics.md) to see the code in action. + +>>This project is an excellent addition to your portfolio. I can't wait to see what creative names you've given to this script. diff --git a/Challenges/Day_4/function_scripts_file.sh b/Challenges/Day_4/function_scripts_file.sh new file mode 100644 index 00000000..5650e6c1 --- /dev/null +++ b/Challenges/Day_4/function_scripts_file.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +view_system_metrics () { + cpu_usage=`top -bn2 | grep '%Cpu' | tail -1 | grep -P '(....|...) id,' | awk -v cores=$(nproc --all) '{print "CPU Usage: " ($8/cores) "%"}'` + memory_usage=`free | grep Mem | awk '{print "Memory usage: " $3/$2 * 100.0 "%"}'` + disk_usage=`df --total -hl | grep total | awk '{print "Disk usage: " $5}'` + + echo "$cpu_usage " " $memory_usage " " $disk_usage" +} \ No newline at end of file diff --git a/Challenges/Day_4/metrics_monitoring.sh b/Challenges/Day_4/metrics_monitoring.sh new file mode 100755 index 00000000..ff9cae77 --- /dev/null +++ b/Challenges/Day_4/metrics_monitoring.sh @@ -0,0 +1,91 @@ +############################################################################################## +#!/bin/bash # +############################################################################################## +# Author : Gurudeo ray # +############################################################################################## +# # +# About : Developed a script to monitor metrics with sleep mechanism # +# # +# # +############################################################################################## +# # +# Execution : sudo ./ # +# # +# Example : sudo ./metrics_monitoring.sh # +# # +######################### Script file sourcin section #################################### + +source function_scripts_file.sh +source monitor_process.sh + +############################ End of script file sourcin section ############################# + +echo "---- Monitoring Metrics Script ----" +echo "" + +# Menu choices +echo "1. View syetem metrics." +echo "2. Monitor a specific service." +echo "3. Exit." +echo "" +echo -n "Enter a menu choice [1 to 3]: " + +# while loop to execute menu in loop +while : +do + read choice + + case $choice in + + ######### Case 1 : View syetem metrics ###### + 1) + echo "---- System Metrics ----" + # function to print system metrics. + view_system_metrics + echo "" + while : + do + read -p "Press enter to continue..." metrics + if [ "$metrics" == "" ]; then + echo "" + view_system_metrics + else + break + fi + done;; + + ######### Case 2 : Monitor a specific service ###### + 2) + echo "Monitor a specific service" + + while : + do + read -p "Enter the name of the service: " service_name + if [ "$service_name" != "" ]; then + bash monitor_process.sh $service_name + read -p "Press enter to continue [press EXIT to exit]:" decision + + if [ "$decision" != "" ]; then + break + else + continue + fi + else + echo "" + echo "ERROR: Please enter a valid service name." + fi + done + ;; + + ######### Case 3 : Exit ###### + 3) exit;; + + *) + echo "WARNING: Please enter valid choice." + echo "" + ;; + esac + echo -n "Enter a menu choice [1 to 3]: " + echo "" + +done diff --git a/Challenges/Day_4/monitor_process.sh b/Challenges/Day_4/monitor_process.sh new file mode 100755 index 00000000..3f3b91b6 --- /dev/null +++ b/Challenges/Day_4/monitor_process.sh @@ -0,0 +1,76 @@ +############################################################################################## +#!/bin/bash # +############################################################################################## +# Author : Gurudeo ray # +############################################################################################## +# # +# About : Developed a script to monitor a process if it is running, if not ? try to restart. # +# # +# # +############################################################################################## +# # +# Execution : sudo ./ (Recommended to execute with sudo user) # +# # +# Example : sudo ./monitor_process.sh httpd # +# # +############################################################################################## + +# Function to check whether process is running or not + +########### Start is_process_running() ####################################################### + +is_process_running () { + systemctl status $1 1>/dev/null 2>/dev/null + return $? +} + +########### End of is_process_running() ###################################################### + +# Function to start and enable the service + +########### Start start_process () ########################################################### + +start_process () { + counter=0 + + while [ $counter -lt 3 ]; do + + systemctl start $1 1>/dev/null 2>/dev/null + if [ $? -eq 0 ]; then + echo "$1 service is up and running..." + systemctl enable $1 1>/dev/null 2>/dev/null + exit 0 + else + if [ $counter -eq 2 ]; then + echo "" + echo "WARNING: We tried 3 times to start the $1 service but could not start, Please check the service name or please manually start it." + echo "" + exit 1 + else + counter=`expr $counter + 1` + fi + fi + done + +} + +########### End of start_process () ######################################################### + +# Check if service name is passed as a argument and check the process status +if [ $# -eq 1 ]; then + is_process_running $1 + if [ $? -eq 0 ]; then + echo "$1 is running..." + else + echo "ERROR: $1 is not running...!" + echo "" + echo "Please Note - We are starting the $1 service...!" + start_process $1 + fi +else + echo "ERROR: Please pass the service name with script or check the execution process of script as below: " + echo "" + head -16 monitor_process.sh +fi + +################# End of script ############################################################ \ No newline at end of file diff --git a/Challenges/Day_4/usr_example_interaction.md b/Challenges/Day_4/usr_example_interaction.md new file mode 100644 index 00000000..4e9d5c92 --- /dev/null +++ b/Challenges/Day_4/usr_example_interaction.md @@ -0,0 +1,70 @@ +# Example Interaction - Monitoring Nginx Process + +In this example, we will demonstrate the usage of the `monitor_process.sh` script to monitor the Nginx process on a Linux system. The script will check if the Nginx process is running and restart it if it's not. + +## Prerequisites + +Before proceeding, make sure you have the following: + +- A Linux-based system (Ubuntu, CentOS, etc.) with Nginx installed. + +> Assuming the script is saved as monitor_process.sh, and the process to monitor is Nginx. + +1. Execute the monitor_process.sh script with "nginx" as the process name to monitor: + +``` +./monitor_process.sh nginx +``` + +The script will check if the Nginx process is running and provide appropriate output based on its status. + +2. Simulate Nginx Process Stopping + +For demonstration purposes, let's simulate the Nginx process stopping. You can stop the Nginx service using the following command: + +``` +sudo systemctl stop nginx +``` + +3. Monitor the Nginx Process + +Now, let's run the monitor_process.sh script again to see how it automatically restarts the Nginx process: + +The script will detect that the Nginx process is not running and attempt to restart it. It will display messages indicating the attempt to restart the process. + +The script will attempt to restart the process automatically for three times: + +``` +Process Nginx is not running. Attempting to restart... +Process Nginx is not running. Attempting to restart... +Process Nginx is not running. Attempting to restart... +Maximum restart attempts reached. Please check the process manually. + +``` + +4. Check Nginx Status + +After the script attempts to restart the Nginx process, you can verify its status using the following command: + +``` +sudo systemctl status nginx +``` + +"You should see that the Nginx process is **now running**." + +5. Automation (Optional) + To automate the process monitoring, you can set up a cron job to run the script at regular intervals. + + + + +------------------------------------------------------------------------------------------------------------------------------------------- + + + + +![Ssofterminal](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/4939241c-66f7-4445-bab5-6e8e8faa9d3f) + +------------------------------------------------------------------------------------------------------------------------------------------- + +![Ssofterminal](https://github.com/prajwalpd7/BashBlaze-7-Days-of-Bash-Scripting-Challenge/assets/71492927/b54073b7-2ba6-4727-8d74-bb64a25b273e) diff --git a/Challenges/Day_4/usr_interaction_with_metrics.md b/Challenges/Day_4/usr_interaction_with_metrics.md new file mode 100644 index 00000000..541d2ff0 --- /dev/null +++ b/Challenges/Day_4/usr_interaction_with_metrics.md @@ -0,0 +1,105 @@ +--- + +## Monitoring Metrics Script - User Interaction Example + +Assume we have a script called `monitoring_script.sh` that implements the tasks mentioned in the challenge. + +1. **Launching the Script** + + Open a terminal and navigate to the directory where `monitoring_script.sh` is located. Execute the script using the following command: + + ```bash + $ ./monitoring_script.sh + ``` + +2. **Main Menu** + + Once the script starts, you'll see a simple menu displayed on the terminal: + + ``` + ---- Monitoring Metrics Script ---- + + 1. View System Metrics + 2. Monitor a Specific Service + 3. Exit + ``` + +3. **View System Metrics** + + If you choose option 1, the script will display the current system metrics, including CPU usage, memory usage, and disk space usage. The output might look like this: + + ``` + ---- System Metrics ---- + + CPU Usage: 8% Mem Usage: 24% Disk Space: 62% + + Press Enter to continue... + ``` + + The script waits for a moment (based on the specified sleep interval) before displaying the metrics again. + +4. **Monitor a Specific Service** + + If you choose option 2, the script will prompt you to enter the name of the service you want to monitor. Let's say you want to monitor Nginx. Enter "nginx" when prompted: + + ``` + ---- Monitor a Specific Service ---- + + Enter the name of the service to monitor: nginx + ``` + + The script will check the status of Nginx and display whether it is running or not: + + ``` + ---- Nginx Status ---- + + Nginx is running. + + Press Enter to continue... + ``` + + If Nginx is not running, you'll see: + + ``` + ---- Nginx Status ---- + + Nginx is not running. + + Do you want to start Nginx? (Y/N): _ + ``` + + If you choose "Y," the script will attempt to start Nginx. + +5. **Exit** + + If you choose option 3, the script will gracefully exit, and the terminal prompt will be returned to you. + +6. **Error Handling** + + In case of any errors, such as invalid input or failed commands, the script will display appropriate error messages. For example: + + ``` + Error: Invalid option. Please choose a valid option (1, 2, or 3). + ``` + +--- + +Note: The above example assumes that the script is implemented according to the tasks mentioned in the challenge. + +### Get Help and Stay Connected + +If you have any questions or need assistance during the challenge, feel free to connect with me on LinkedIn. Click the button below to visit my profile: + +[![LinkedIn Profile](../../assets/icons8-linkedin-96(@2x).png)](https://www.linkedin.com/in/d-prajwal/) + +### Reference Videos + +If you are new to bash scripting or need some helpful resources, check out these reference videos for beginners: + +1. [EASIEST Shell Scripting Tutorial for Beginners](https://youtu.be/_-D6gkRj7xc) +2. [ADVANCED Shell Scripting Tutorial](https://youtu.be/UYstAfqkLtg) +3. [New ADVANCED Shell Scripting Tutorial for DevOps](https://youtu.be/IoUGl76kyLk) + +These videos will give you a solid foundation in bash scripting and help you tackle this challenge with confidence. + +Happy scripting and best of luck with the challenge! Don't hesitate to reach out if you need any assistance. Let's make this challenge a great learning experience together! diff --git a/Challenges/Day_5/Log_Analyzer.md b/Challenges/Day_5/Log_Analyzer.md new file mode 100644 index 00000000..527814d7 --- /dev/null +++ b/Challenges/Day_5/Log_Analyzer.md @@ -0,0 +1,56 @@ +# Day 5: Bash Scripting Challenge - Log Analyzer and Report Generator + +## Challenge Title: Log Analyzer and Report Generator + +## Scenario + +You are a system administrator responsible for managing a network of servers. Every day, a log file is generated on each server containing important system events and error messages. As part of your daily tasks, you need to analyze these log files, identify specific events, and generate a summary report. + +## Task + +Write a Bash script that automates the process of analyzing log files and generating a daily summary report. The script should perform the following steps: + +1. **Input:** The script should take the path to the log file as a command-line argument. + +2. **Error Count:** Analyze the log file and count the number of error messages. An error message can be identified by a specific keyword (e.g., "ERROR" or "Failed"). Print the total error count. + +3. **Critical Events:** Search for lines containing the keyword "CRITICAL" and print those lines along with the line number. + +4. **Top Error Messages:** Identify the top 5 most common error messages and display them along with their occurrence count. + +5. **Summary Report:** Generate a summary report in a separate text file. The report should include: + + - Date of analysis + - Log file name + - Total lines processed + - Total error count + - Top 5 error messages with their occurrence count + - List of critical events with line numbers + +6. **Optional Enhancement:** Add a feature to automatically archive or move processed log files to a designated directory after analysis. + +## Tips + +- Use `grep`, `awk`, and other command-line tools to process the log file. +- Utilize arrays or associative arrays to keep track of error messages and their counts. +- Use appropriate error handling to handle cases where the log file doesn't exist or other issues arise. + +## Sample Log File + +A sample log file named `sample_log.log` has been provided in the same directory as this challenge file. You can use this file to test your script. + +## How to Participate + +1. Clone this repository or download the challenge file from the provided link. +2. Write your Bash script to complete the log analyzer and report generator task. +3. Use the provided `sample_log.log` or create your own log files for testing. +4. Test your script with various log files and scenarios to ensure accuracy. +5. Submit your completed script by the end of Day 5 of the 7-day Bash scripting challenge. + +## Submission + +Submit your completed script by [creating a pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) or sending the script file to the challenge organizer. + +Good luck and happy scripting! + +--- diff --git a/Challenges/Day_5/Sample_Log_Data.md b/Challenges/Day_5/Sample_Log_Data.md new file mode 100644 index 00000000..3ddc8a69 --- /dev/null +++ b/Challenges/Day_5/Sample_Log_Data.md @@ -0,0 +1,77 @@ +# Welcome, Challenger! + +## Sample Log Data for Testing + +Congratulations on reaching Day 5 of the 7-day Bash scripting challenge! To assist you in testing your log analyzer and report generator script, we have something below. + +## Create Your Own Data + +Feeling adventurous? If you want to go beyond the provided sample data(which you won't find because i haven't uploaded it ), you can generate your own log data using the `log_generator.sh` script. This script allows you to create log files with custom log levels, error messages, and line counts. + +**How to Generate Your Own Log Data:** + +1. Execute the `log_generator.sh` script with the desired log file path and the number of lines you want to generate. +2. Customize the `log_levels` and `error_messages` arrays in the script to tailor the log data to your needs. + +Remember, the more diverse log data you test with, the better you can fine-tune your script! + +Wishing you the best of luck in this challenge. Happy scripting! + +--- + +```Bash +#!/bin/bash + +# Usage: ./log_generator.sh + +if [ "$#" -ne 2 ]; then + echo "Usage: $0 " + exit 1 +fi + +log_file_path="$1" +num_lines="$2" + +if [ -e "$log_file_path" ]; then + echo "Error: File already exists at $log_file_path." + exit 1 +fi + +# List of possible log message levels +log_levels=("INFO" "DEBUG" "ERROR" "WARNING" "CRITICAL") + +# List of possible error messages +error_messages=("Failed to connect" "Disk full" "Segmentation fault" "Invalid input" "Out of memory") + +# Function to generate a random log line +generate_log_line() { + local log_level="${log_levels[$((RANDOM % ${#log_levels[@]}))]}" + local error_msg="" + if [ "$log_level" == "ERROR" ]; then + error_msg="${error_messages[$((RANDOM % ${#error_messages[@]}))]}" + fi + echo "$(date '+%Y-%m-%d %H:%M:%S') [$log_level] $error_msg - $RANDOM" +} + +# Create the log file with random log lines +touch "$log_file_path" +for ((i=0; i> "$log_file_path" +done + +echo "Log file created at: $log_file_path with $num_lines lines." + +``` + +--- + +Usage: +To use the log generator script, participants can execute the following command: + +``` +./log_generator.sh /path/to/logfile.log 100 +``` + +> This will create a log file named "logfile.log" in the specified path with 100 random log lines. Participants can adjust the number of lines as needed for testing their log analyzer and report generator scripts. + +The log lines generated will have timestamps, log levels (INFO, DEBUG, ERROR, WARNING, CRITICAL), and randomly chosen error messages for lines with "ERROR" log level. diff --git a/Challenges/solution_day1_script.sh b/Challenges/solution_day1_script.sh deleted file mode 100644 index 2b904ef1..00000000 --- a/Challenges/solution_day1_script.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -# First line of the script is the shebang which tells the system how to execute - -# Task 2: Echo -echo "Scripting is fun with @TWS" - -# Task 3: Variables -variable1="Hello" -variable2="Bash" - -# Task 4: Using Variables -greeting="$variable1, $variable2!" -echo "$greeting Welcome to the world of Bash scripting!" - -# 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 6: Wildcards -echo "Files with .txt extension in the current directory:" -ls *.txt - - - -#Make sure to provide execution permission with the following command: -#chmod +x day1_script.sh