0% found this document useful (0 votes)
8 views

Script

The document outlines a series of tasks for a DevOps and Cloud Computing assignment, including scripts for file management, system health checks, user account management, automated backups, a simple to-do list, software installation, and text file processing. Each task includes a description and a corresponding Bash script to accomplish the specified objectives. The assignment is due on September 16, 2024, and is submitted by Shashank Shekhar Singh.

Uploaded by

Shekhar Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Script

The document outlines a series of tasks for a DevOps and Cloud Computing assignment, including scripts for file management, system health checks, user account management, automated backups, a simple to-do list, software installation, and text file processing. Each task includes a description and a corresponding Bash script to accomplish the specified objectives. The assignment is due on September 16, 2024, and is submitted by Shashank Shekhar Singh.

Uploaded by

Shekhar Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Name : Shashank Shekhar Singh

Reg Email : [email protected]


Course Name : DevOps and Cloud Computing “August 2024”
Assignment : File Management Script
Submission Date : 16th Sep 2024

Task1: File Management Script


Write a Bash script that:
Creating a directory named “backup” in the user’s home directory.
Copies all .txt files from the current directory into the “backup” directory.
Append the current date and time to the filenames of the copies files.

#!/bin/bash

# Step 1: Create a "backup" directory in the user's home directory

backup_dir="$HOME/backup"

mkdir -p "$backup_dir"

# Step 2: Get the current date and time in the format YYYY-MM-DD_HH-MM-SS

current_datetime=$(date +"%Y-%m-%d_%H-%M-%S")

# Step 3: Loop through all .txt files in the current directory

for file in *.txt; do

# Check if there are any .txt files

if [[ -f "$file" ]]; then

# Extract the filename without extension


filename=$(basename "$file" .txt)

# Append the current date and time to the filename and copy to the backup directory

cp "$file" "$backup_dir/${filename}_$current_datetime.txt"

fi

done

echo "Backup completed."

Task 2: System Health Check


Check the system’s CPU and memory usage

Report if the CPU usage is above 80% or if the available memory is below 20%

Logs the results to a file named system_health.log

#!/bin/bash

# Log file location

log_file="system_health.log"

# Get current date and time

current_time=$(date +"%Y-%m-%d %H:%M:%S")

# Check CPU usage (average over 1 minute)

cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')

# Check memory usage

total_memory=$(free | grep Mem | awk '{print $2}')

used_memory=$(free | grep Mem | awk '{print $3}')

memory_usage=$(( used_memory * 100 / total_memory ))


# Start logging

echo "System Health Check - $current_time" >> "$log_file"

# Check CPU usage

if (( $(echo "$cpu_usage > 80" | bc -l) )); then

echo "CPU usage is above 80%: ${cpu_usage}%." >> "$log_file"

else

echo "CPU usage is normal: ${cpu_usage}%." >> "$log_file"

fi

# Check memory usage

if (( memory_usage > 80 )); then

echo "Memory usage is above 80%: ${memory_usage}%." >> "$log_file"

else

echo "Memory usage is normal: ${memory_usage}%." >> "$log_file"

fi

echo "System health check completed and logged."

Task 3 User Account Management


Write a script that :

Reads a list of usernames from a file (eg , user_list.txt)

Creates a new user for each username

Generates a random password for each user and saves the username and password
to a file named credentials.txt
#!/bin/bash

# Input and output files

user_list="user_list.txt"

credentials_file="credentials.txt"

# Function to generate random password

generate_password() {

# Generate a random 12-character password (letters, numbers, special characters)

openssl rand -base64 12

# Clear or create the credentials file

> "$credentials_file"

# Loop through each username in the user_list file

while IFS= read -r username || [[ -n "$username" ]]; do

# Check if user already exists

if id "$username" &>/dev/null; then

echo "User $username already exists, skipping..."

else

# Create a new user without a home directory (-M) and without a password (-s
/usr/sbin/nologin)

sudo useradd -m "$username"

# Generate a random password for the new user

password=$(generate_password)

# Set the password for the user


echo "$username:$password" | sudo chpasswd

# Save the username and password to the credentials file

echo "Username: $username, Password: $password" >> "$credentials_file"

echo "User $username created successfully."

fi

done < "$user_list"

echo "All users have been processed. Credentials saved to $credentials_file."

Task 4 Automated Backup


Create a script that :

Takes a directory path as input from the user.

Compresses the directory into a .tar.gz file

Saves the compressed file with a name that includes the current date (e.g ,
backup_2023-08-20.tar.gz)

#!/bin/bash

# Prompt the user for the directory path

read -p "Enter the directory path you want to back up: " directory_path

# Check if the directory exists

if [[ ! -d "$directory_path" ]]; then

echo "Error: Directory does not exist!"

exit 1

fi

# Get the current date in the format YYYY-MM-DD

current_date=$(date +"%Y-%m-%d")
# Get the name of the directory (basename)

directory_name=$(basename "$directory_path")

# Define the backup file name

backup_file="backup_${directory_name}_$current_date.tar.gz"

# Compress the directory into a .tar.gz file

tar -czf "$backup_file" -C "$(dirname "$directory_path")" "$directory_name"

# Notify the user

echo "Backup of '$directory_path' completed successfully!"

echo "Backup file: $backup_file"

Task 5 Simple To-Do List


Create a bash script that:

Implement a simple command-line to-do list.

Allows the user to add tasks , view tasks and remove tasks.

Saves the tasks to a file (e.g , todo.txt)

#!/bin/bash

# File to store tasks

todo_file="todo.txt"

# Function to add a task

add_task() {

read -p "Enter the task to add: " task

if [[ -n "$task" ]]; then

echo "$task" >> "$todo_file"


echo "Task added successfully!"

else

echo "Error: Task cannot be empty."

fi

# Function to view tasks

view_tasks() {

if [[ ! -s "$todo_file" ]]; then

echo "No tasks found."

else

echo "Your to-do list:"

cat -n "$todo_file"

fi

# Function to remove a task

remove_task() {

if [[ ! -s "$todo_file" ]]; then

echo "No tasks to remove."

return

fi

view_tasks

read -p "Enter the task number to remove: " task_number

if [[ "$task_number" =~ ^[0-9]+$ ]]; then

sed -i "${task_number}d" "$todo_file"

echo "Task removed successfully!"

else

echo "Invalid input. Please enter a valid task number."

fi

}
# Main menu loop

while true; do

echo

echo "Simple To-Do List"

echo "1. Add task"

echo "2. View tasks"

echo "3. Remove task"

echo "4. Exit"

read -p "Choose an option [1-4]: " option

case $option in

1) add_task ;;

2) view_tasks ;;

3) remove_task ;;

4) echo "Goodbye!"; exit 0 ;;

*) echo "Invalid option. Please choose between 1-4." ;;

esac

done

Task 6 Automated Software installation


Write a script that :

Reads a list of software package names from a file (e.g packages.txt)

Installs each package using the appropriate package manager (apt, yum, etc).

Logs the installation status of each package.

#!/bin/bash

# File containing the list of packages to be installed

package_file="packages.txt"

# Log file to record installation status


log_file="installation_log.txt"

# Determine the package manager (apt for Debian-based, yum for RedHat-based)

if command -v apt &> /dev/null; then

package_manager="apt"

update_command="sudo apt update"

install_command="sudo apt install -y"

elif command -v yum &> /dev/null; then

package_manager="yum"

update_command="sudo yum update -y"

install_command="sudo yum install -y"

else

echo "No supported package manager found (apt or yum)." >> "$log_file"

exit 1

fi

# Update package lists

echo "Updating package lists using $package_manager..." >> "$log_file"

$update_command >> "$log_file" 2>&1

# Read packages from the package_file and install each one

while IFS= read -r package || [[ -n "$package" ]]; do

# Check if the package name is not empty

if [[ -n "$package" ]]; then

echo "Installing $package..." >> "$log_file"

# Attempt to install the package

if $install_command "$package" >> "$log_file" 2>&1; then

echo "$package installed successfully." >> "$log_file"

else

echo "Error: Failed to install $package." >> "$log_file"

fi

fi
done < "$package_file"

echo "Software installation completed. Check $log_file for details."

Task 7 Text File Processing


Create a script that:

Takes a text file as input

Count and display the number of lines, words and charecters in the file.

Finds and displays the longest word in the file.

#!/bin/bash

# Check if a file was provided as input

if [[ -z "$1" ]]; then

echo "Error: No file provided. Please provide a text file as input."

exit 1

fi

# Check if the file exists

if [[ ! -f "$1" ]]; then

echo "Error: File does not exist."

exit 1

fi

# Get the file name from the argument

file="$1"

# Count the number of lines, words, and characters

num_lines=$(wc -l < "$file")


num_words=$(wc -w < "$file")

num_chars=$(wc -m < "$file")

# Display the results

echo "File: $file"

echo "Number of lines: $num_lines"

echo "Number of words: $num_words"

echo "Number of characters: $num_chars"

# Find the longest word in the file

longest_word=$(tr -s '[:space:][:punct:]' '\n' < "$file" | awk '{ if (length > max_length) { max_length = length;
longest_word = $0 }} END { print longest_word }')

# Display the longest word

if [[ -n "$longest_word" ]]; then

echo "Longest word: $longest_word"

else

echo "No words found in the file."

fi

You might also like