Monitor Website Availability

It doesn’t make much sense to use DDNS on an IPv6 web site. Implementing a script to check the status and send email alert should be enough.

# web_monitor.py
import smtplib
import requests

# replace with your own data
target_url = 'your_url_address'
smtp_server = 'your_smtp_server_address'
smtp_port = 'your_smtp_port_number' # for example: 587
smtp_id = 'your_smtp_login_id'
smtp_password = 'your_smtp_login_password'
email_from = 'sent_from_email_address'
email_to = 'sent_to_email_address'

# subject, header and body
subject = 'Subject: Alert for ' + target_url + '\n'
header = 'To:' + email_to + '\n' + 'From: ' + email_from + '\n' + subject
body = "Your webserver " + target_url + " is DOWN."
message = header + body

# define function to send email
def send_alert(msg):
    smtpObj = smtplib.SMTP(smtp_server, smtp_port)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.login(smtp_id, smtp_password)
    smtpObj.sendmail(email_from, email_to,msg)
    smtpObj.quit()

# define function to check status of web server
def url_check(url):
    try:
        #Get Url
        get=requests.get(url)
        # if the request succeeds
        if get.status_code == 200:
            print(url + ": is reachable")
        else:
            print(url + ": is NOT reachable, status_code:" + get.status_code)
            send_alert(message)
    #Exception
    except requests.exceptions.RequestException as e:
        # print URL with Errs
        send_alert(message)
        raise SystemExit(f"{url}: is Not reachable \nErr: {e}")

if __name__ == '__main__':
    url_check(target_url)

Create a cron job to run the script in every 5 minutes.

*/5 * * * * /usr/bin/python3 [path_to_the_script]/web_monitor.py

Leave a Reply