Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make the watchdog not monitor Python scripts' operations such as opening and modifying files #1067

Open
chanly921 opened this issue Sep 6, 2024 · 5 comments

Comments

@chanly921
Copy link

chanly921 commented Sep 6, 2024

How to make the watchdog not monitor Python scripts' operations such as opening and modifying files, modification, and other operations. Here is a simple example, when I open a file, I will execute the decrypt_file function, and the opening and modification of the file by the decrypt_file function will be detected by the watchdog.

def read_file(file_path: str) -> bytes:
    with open(file_path, 'rb') as f:
        data = f.read()
    return data


def encrypt_file(file_path: str):
    data = read_file(file_path)
    with open(file_path, 'wb') as f:
        print('File successfully encrypted...')
        f.write(data)


def decrypt_file(file_path: str):
    data = read_file(file_path)
    with open(file_path, 'wb') as f:
        print('File successfully decrypted...')
        f.write(data)


class FileEncryptHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.is_directory and re.search(FILE_PATTERN, os.path.basename(event.src_path)):
            print(f'File {os.path.basename(event.src_path)} modified...')
            encrypt_file(event.src_path)

    def on_opened(self, event):
        if not event.is_directory and re.search(FILE_PATTERN, os.path.basename(event.src_path)):
            print(f'File {os.path.basename(event.src_path)} opened up...')
            decrypt_file(event.src_path)

2024-09-06_17-31

@chanly921 chanly921 changed the title How to make watchdog not monitor the opening of files by Python scripts How to make the watchdog not monitor Python scripts' operations such as opening and modifying files Sep 6, 2024
@BoboTiG
Copy link
Collaborator

BoboTiG commented Sep 6, 2024

I am not sure to understand what you want 🤔

@chanly921
Copy link
Author

I want to modify the target file in the on_opened and on_madified methods of watchdog. The action of modifying target file is not monitored by watchdog.

@BoboTiG
Copy link
Collaborator

BoboTiG commented Sep 8, 2024

Can you share the code?

@chanly921
Copy link
Author

Of course. After executing a Python program, opening Word will result in the current situation. After opening Word, executing the Python program and making modifications to Word will also result in the current situation.

import hashlib
import os
import re
import time

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


def read_file(file_path: str) -> bytes:
    with open(file_path, 'rb') as f:
        data = f.read()
    return data


def encrypt_file(file_path: str):
    try:
        data = read_file(file_path)
        if data[:len(key)] == key:
            return
        with open(file_path, 'wb') as f:
            print('File successfully encrypted...')
            f.write(key + data)
    except Exception:
        pass


def decrypt_file(file_path: str):
    try:
        data = read_file(file_path)
        if data[:len(key)] != key:
            return
        with open(file_path, 'wb') as f:
            print('File successfully decrypted...')
            f.write(data[len(key):])
    except Exception:
        pass


class FileEncryptHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.is_directory and re.search(r'^(?!.*\.\~).*\.doc$|^(?!.*\.\~).*\.docx$', event.src_path):
            print(f'File {os.path.basename(event.src_path)} modified...')
            encrypt_file(event.src_path)

    def on_opened(self, event):
        if not event.is_directory and re.search(r'^(?!.*\.\~).*\.doc$|^(?!.*\.\~).*\.docx$', event.src_path):
            print(f'File {os.path.basename(event.src_path)} opened up...')
            decrypt_file(event.src_path)


def start_monitoring():
    handler = FileEncryptHandler()
    observer = Observer()
    observer.schedule(handler, folder, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


if __name__ == "__main__":
    print('Start...')
    folder = r'/home/c/test'  # Change to test directory
    key = hashlib.sha256('12gs5349dadh2894lr34'.encode()).digest()
    start_monitoring()
    print('End...')

@hmiefert
Copy link

hmiefert commented Nov 27, 2024

You might want to check the different EventHandlers. I guess in your case you'd want to use PatternMatching or RegexMatching.

from watchdog.events import LoggingEventHandler, FileSystemEventHandler, RegexMatchingEventHandler, PatternMatchingEventHandler

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants