# 60 Days DevOps Challenge: Day 2

### ***Challenge 1*** : Write a simple Bash script that prints “Hello DevOps” along with the current date and time.\*

```bash
#!/bin/bash

echo "Hello DevOps! Today's date and time is: $(date)"
```

```plaintext
MacBook-Pro challenge1 % ./hello_devops.sh 
Hello DevOps! Today's date and time is: Tue Mar 18 21:26:28 IST 2025
```

### ***Challenge 2*** : Create a script that checks if a website (e.g.,\* [`https://www.learnxops.com`](https://www.learnxops.com)*) is reachable using* `curl` *or* `ping`*. Print a success or failure message.*

```bash
#!/bin/bash

# Define the website to check
WEBSITE="https://www.learnxops.com"
DOMAIN="learnxops.com"

# Check website availability using curl
if curl -Is "$WEBSITE" --max-time 5 | head -n 1 | grep -q "200\|301\|302"; then
    echo "✅ Success: $WEBSITE is reachable via curl!"
else
    echo "⚠️ Curl check failed, trying ping..."
    
    # Check website availability using ping
    if ping -c 2 -W 2 "$DOMAIN" > /dev/null 2>&1; then
        echo "✅ Success: $DOMAIN is reachable via ping!"
    else
        echo "❌ Failure: $WEBSITE is not reachable via curl or ping."
    fi
fi
```

```plaintext
MacBook-Pro challenge2 % ./check_website.sh 
✅ Success: https://www.learnxops.com is reachable via curl!
```

### ***Challenge 3*** : Write a script that takes a filename as an argument, checks if it exists, and prints the content of the file accordingly.\*

```bash
#!/bin/bash

# Check if a filename argument is provided
if [ $# -eq 0 ]; then
    echo "❌ Error: No filename provided."
    echo "Usage: ./check_file.sh <filename>"
    exit 1
fi

FILENAME="$1"

# Check if the file exists
if [ -f "$FILENAME" ]; then
    echo "✅ File '$FILENAME' found. Displaying content:"
    cat "$FILENAME"
else
    echo "❌ Error: File '$FILENAME' does not exist."
fi
```

```plaintext
MacBook-Pro challenge3 % ./check_file.sh /Users/muzakeer/Documents/musaveer_work/hello.txt 
✅ File '/Users/muzakeer/Documents/musaveer_work/hello.txt' found. Displaying content:
Hello! Welcome to the DevOps challenge
```

### ***Challenge 4*** : Create a script that lists all running processes and writes the output to a file named\* `process_list.txt`*.*

```bash
#!/bin/bash

# Define output file
OUTPUT_FILE="process_list.txt"

# List all running processes and write to file
ps aux > "$OUTPUT_FILE"

# Print success message
echo "✅ Process list saved to $OUTPUT_FILE"
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1742314157353/91cfed08-a03f-43ba-8ccf-f5dd0deefe92.png align="center")

### ***Challenge 5*** : Write a script that installs multiple packages at once (e.g.,\* `git`*,* `vim`*,* `curl`*). The script should check if each package is already installed before attempting installation.*

```bash
#!/bin/bash

# Define the list of packages to install
PACKAGES=("git" "vim" "curl")

# Loop through each package and check if it's installed
for PACKAGE in "${PACKAGES[@]}"; do
    if dpkg -l | grep -qw "$PACKAGE"; then
        echo "✅ $PACKAGE is already installed."
    else
        echo "⏳ Installing $PACKAGE..."
        sudo apt-get install -y "$PACKAGE" && echo "✅ $PACKAGE installed successfully." || echo "❌ Failed to install $PACKAGE."
    fi
done
```

![](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/aa5ac129-029c-4683-bed4-086cbe5e1e4b/Screenshot_2025-02-28_at_8.20.58_PM.png?t=1740754498 align="left")

```plaintext
MacBook-Pro challenge5 % ./install_packages.sh 
./install_packages.sh: line 11: dpkg: command not found
⏳ Installing git...
Password:
sudo: apt-get: command not found
❌ Failed to install git.
./install_packages.sh: line 11: dpkg: command not found
⏳ Installing vim...
sudo: apt-get: command not found
❌ Failed to install vim.
./install_packages.sh: line 11: dpkg: command not found
⏳ Installing curl...
sudo: apt-get: command not found
❌ Failed to install curl.
```

### ***Challenge 6*** : Create a script that monitors CPU and memory usage every 5 seconds and logs the results to a file.\*

```bash
#!/bin/bash

# Define the log file
LOG_FILE="resource_usage.log"

echo "Monitoring CPU and Memory usage... Logs will be saved in $LOG_FILE"
echo "Timestamp          | CPU (%) | Memory (%)" > "$LOG_FILE"

# Infinite loop to log system usage every 5 seconds
while true; do
    TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
    
    # Get CPU usage
    CPU_USAGE=$(top -l  2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }')
    
    # Get Memory usage
    MEM_USAGE=$(top -l 1 | grep -E "^Phys")
    
    # Write data to the log file
    echo "$TIMESTAMP |  $CPU_USAGE  |  $MEM_USAGE" >> "$LOG_FILE"
    
    # Wait for 5 seconds
    sleep 5
done
```

```plaintext
Timestamp          | CPU (%) | Memory (%)
2025-03-18 22:01:43 |  10.11%  |  PhysMem: 15G used (1619M wired, 601M compressor), 248M unused.
2025-03-18 22:01:50 |  17.22%  |  PhysMem: 15G used (1677M wired, 601M compressor), 402M unused.
```

### ***Challenge 7*** : Write a script that automatically deletes log files older than 7 days from\* `/var/log`*.*

```bash
#!/bin/bash

# Define log directory
LOG_DIR="/var/log"

# Define file age threshold (in days)
DAYS=7

# Find and delete log files older than 7 days
find "$LOG_DIR" -type f -name "*.log" -mtime +$DAYS -exec rm -f {} \;

# Print success message
echo "✅ Deleted log files older than $DAYS days from $LOG_DIR."
```

```plaintext
MacBook-Pro challenge7 % sudo ./clean_old_logs.sh 
Password:
✅ Deleted log files older than 7 days from /var/log.
```

### ***Challenge 8*** : Automate user account creation – Write a script that takes the username as an argument, checks, if the user exists, gives the message “user already exists“ else creates a new user, adds it to a “devops“ group, and sets up a default home directory.\*

```bash
#!/bin/bash

# Check if a username is provided
if [ $# -eq 0 ]; then
    echo "❌ Error: No username provided."
    echo "Usage: sudo ./create_user.sh <username>"
    exit 1
fi

USERNAME="$1"
GROUP="devops"

# Check if user already exists
if id "$USERNAME" &>/dev/null; then
    echo "✅ User '$USERNAME' already exists."
else
    # Create the group if it doesn't exist
    if ! getent group "$GROUP" > /dev/null; then
        echo "⏳ Creating group '$GROUP'..."
        sudo groupadd "$GROUP"
    fi

    # Create user with home directory and add to group
    echo "⏳ Creating user '$USERNAME'..."
    sudo useradd -m -s /bin/bash -G "$GROUP" "$USERNAME"

    # Set a default password (optional, force change on first login)
    echo "$USERNAME:ChangeMe123" | sudo chpasswd
    sudo passwd --expire "$USERNAME"

    echo "✅ User '$USERNAME' created successfully and added to group '$GROUP'."
    echo "ℹ️ Default password: ChangeMe123 (User must change it on first login)"
fi
```

```plaintext
✅ User 'musaveer' created successfully and added to group 'devops'.
ℹ️ Default password: ChangeMe123 (User must change it on first login)
```

### ***Challenge 9*** : Use\* `awk` *or* `sed` *in a script to process a log file and extract only error messages.*

```bash
#!/bin/bash

# Define log file path
LOG_FILE="/var/log/syslog"  # Change this to your log file
OUTPUT_FILE="error_messages.log"

# Check if log file exists
if [ ! -f "$LOG_FILE" ]; then
    echo "❌ Error: Log file '$LOG_FILE' not found!"
    exit 1
fi

# Extract error messages using awk
awk '/error|ERROR|Error/ {print}' "$LOG_FILE" > "$OUTPUT_FILE"

# Alternatively, use sed:
# sed -n '/error\|ERROR\|Error/p' "$LOG_FILE" > "$OUTPUT_FILE"

echo "✅ Extracted error messages saved to '$OUTPUT_FILE'."
```

```plaintext
MacBook-Pro challenge9 % ./extract_errors.sh 
❌ Error: Log file '/var/log/syslog' not found!
```

### ***Challenge 10*** : Set up a cron job that runs a script to back up (zip/tar) a directory daily.\*

```bash
#!/bin/bash

# Define backup directory and destination
SOURCE_DIR="/path/to/directory"  # Change this to the directory you want to back up
BACKUP_DIR="/path/to/backup"
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="$BACKUP_DIR/backup_$TIMESTAMP.tar.gz"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Create the backup archive
tar -czf "$BACKUP_FILE" "$SOURCE_DIR"

# Print success message
echo "✅ Backup created: $BACKUP_FILE"
```

```plaintext
MacBook-Pro challenge10 % ./backup.sh 
mkdir: /path: Read-only file system
tar: Failed to open '/path/to/backup/backup_2025-03-18_22-14-14.tar.gz'
✅ Backup created: /path/to/backup/backup_2025-03-18_22-14-14.tar.gz
```

*In conclusion, the 60 Days DevOps Challenge provides a structured and practical approach to enhancing your DevOps skills through a series of hands-on scripting tasks. Each challenge is designed to build foundational knowledge and improve problem-solving abilities in real-world scenarios. By completing these challenges, participants will gain valuable experience in automation, system monitoring, and efficient resource management, which are essential skills in the DevOps field. Embracing this challenge will not only boost your technical expertise but also prepare you for the dynamic and evolving landscape of DevOps practices.*
