Greetings!! I am trying using below watchdog module to monitor a shared path that works fine but I am not getting the idea to generate outlook email alert, after the time span of 20 minutes if no modification or update happening to the specified path. Below is the code:
import os
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
os.system('//fleet.ad/data/Data4/VMSSHARE/its/DOCS')
print("found")
# Defining your own path
path = "//bleet.ad/data/Data4/VMSSHARE/its/DOCS"
print("found")
# Initilaize logging event handler
event_handler = LoggingEventHandler()
# Initialize Observer
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
# Start the observer
observer.start()
try:
while True:
# set the thread sleep time
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
However, tried this piece of code to receive outlook email alerts, but not sure how to make it work with above script:
import os
import smtplib
import requests
EMAIL_ADDRESS = os.environ.get('USER_ID')
EMAIL_PASSWORD = os.environ.get('USER_PASSWORD')
r = requests.get("https://fleet.my.salesforce.com", timeout=5)
#if r.status_code!= 200:
with smtplib.SMTP('smtp.office365.com', 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
subject = 'ALARM: MAPILab is stuck from copying Public folders to destination'
body = 'Make sure server is restarted and it is backed up'
msg = f'Subject:{subject}\n\n{body}'
smtp.sendmail(EMAIL_ADDRESS, 'ryadav@elementcorp.com', msg)
Challenge for me is :
r = requests.get("https://fleet.my.salesforce.com", timeout=5)
Instead of website monitor , how should I ask to look for the code output?
You have to attach methods to your event handler, like this:
my_event_handler.on_created = on_created
my_event_handler.on_deleted = on_deleted
my_event_handler.on_modified = on_modified
my_event_handler.on_moved = on_moved
where the methods look like:
def on_created(event):
print(f"{event.src_path} has been created!")
as described in this blog post: http://thepythoncorner.com/dev/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/
Have your handlers update a last_changed
timestamp variable whenever there is a change. (Since all your handlers do the same thing regardless of what the change was, you could get away with just defining one handler method, maybe call it on_any_change
and attach it to all 4 handler methods. Oh look, the watchdog
docs show that there is an on_any_event
method, so you could just hook into that.)
Then in your while True
loop, if the current time - last_changed
is greater than your threshold, send the email.