Petru Porumbescu

0 %
Petru Porumbescu
AWS Certified Developer & Solutions Architect | Python | Git & GitHub | Terraform | Docker
  • Residence:
    United Kingdom
  • Age:
    35
Licenses & Certifications:
  • AWS Certified Developer
  • AWS Certified Solutions Architect
  • HashiCorp Terraform Associate
  • Python for Beginners
  • Pythonic Programming
  • Developing on AWS
  • Python-based Microservices
English
Romanian
Skills:
  • Amazon Web Services (AWS)
  • Cloud Computing
  • Python Programming
  • Docker
  • Terraform
  • Git and Github
  • Linux, Windows, MacOS
  • WordPress
  • Microsoft Office Suite
  • Microsoft 365
  • Microsoft Teams
  • Slack
  • Leadership
  • Communication
  • Troubleshooting
  • Teamwork & Collaboration

Monitoring Website Availability with Python: A Simple and Useful Script

March 20, 2024

As I continue my journey in learning Python automation, I wanted to share a simple yet useful script that I recently created. This script demonstrates how to monitor the availability of a website and send email notifications when the website is down or inaccessible.The script utilizes the following Python libraries:

  • requests: To send HTTP requests to the website and check its status.
  • smtplib: To send email notifications using SMTP (Simple Mail Transfer Protocol).
  • os: To retrieve email credentials from environment variables.
  • schedule: To schedule the website availability check at regular intervals.
  • time: To introduce a small delay between each iteration of the monitoring loop.

Code Snippets and Practical InsightsHere’s a snippet of the send_notification function, which is a key component of the script:

def send_notification(email_msg):
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.ehlo()
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        msg = f"Subject: Application is down\n{email_msg}"
        smtp.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS, msg)

Challenges and Solutions: During development, I faced the challenge of ensuring the script ran continuously without overloading the system. By incorporating time.sleep(1) it within the main loop, I was able to create an efficient monitoring process that conserves system resources.

Future Enhancements: I am exploring the possibility of integrating this script with a web dashboard, which would offer a more interactive and visual way to monitor website status.

Security Considerations: It’s essential to handle email credentials with care. I recommend using environment variables or secure storage to manage sensitive information. Be mindful of the security risks when considering whether to disable SSL certificate verification, especially in a production setting.

Let’s Connect and Share Insights: Have you embarked on a similar automation project? What challenges did you encounter, and how did you address them? I’d love to hear about your experiences and solutions in the comments below. If you’re interested in more content like this, don’t hesitate to follow my blog and connect with me on LinkedIn.Happy automating with Python!

For those interested in implementing or adapting this script, here’s the complete code:

import requests
import smtplib
import os
import schedule
import time

# Retrieve email address and password from environment variables
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')

def send_notification(email_msg):
    """
    Sends an email notification with the provided message.
    """
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.ehlo()
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        msg = f"Subject: Application is down\n{email_msg}"
        smtp.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS, msg)

def check_website():
    """
    Checks the status of the website and sends a notification if it's down or inaccessible.
    """
    try:
        # Send a GET request to the website
        response = requests.get('https://google.com/')
        
        # Check if the response status code is 200 (OK)
        if response.status_code == 200:
            print('Application is running successfully')
        else:
            print('Application is down. Fix it!')
            msg = f"Application returned: {response.status_code}"
            send_notification(msg)

    except Exception as ex:
        # Handle any exceptions that occur during the request
        print(f'Connection error happened: {ex}')
        msg = "Not accessible!"
        send_notification(msg)

# Schedule the website check to run every 1 hour
schedule.every(1).hours.do(check_website)

while True:
    # Run pending scheduled tasks
    schedule.run_pending()
    
    # Wait for 1 second before the next iteration
    time.sleep(1)

Feel free to adapt and modify this script to suit your specific needs. Remember to set the EMAIL_ADDRESS and EMAIL_PASSWORD environment variables with your valid email credentials before running the script. Additionally, ensure that your email provider allows access from less secure apps or use an app-specific password if you have two-factor authentication enabled.

I hope this script proves to be a valuable tool in your Python automation endeavours. If you have any questions, or suggestions, or would like to share your adaptations of the script, please leave a comment below.

Happy automating with Python!

Posted in Python
Write a comment