Search code examples
pythonfile-watcherwin32con

Is there a way to file watcher on all hard disk drives?


I have a scrip to detect some files created on Hard disk drive using win32file API with python

from win32file import CreateFile, ReadDirectoryChangesW
import win32con

def Watcher():
        ExtensionScan = ['exe', 'dll', 'vbs', 'com', 'jar']
        FILE_LIST_DIRECTORY = 0x0001
        path_to_watch = "c:\\"
        hDir = CreateFile(
            path_to_watch,
            FILE_LIST_DIRECTORY,
            win32con.FILE_SHARE_READ | 
            win32con.FILE_SHARE_WRITE | 
            win32con.FILE_SHARE_DELETE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
        )
        while True:
            Results = ReadDirectoryChangesW (
                hDir,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
                win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
                win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
                win32con.FILE_NOTIFY_CHANGE_SIZE |
                win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
                win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
            )
            for Action, File in Results:
                FullPath = "{}\\{}".format(path_to_watch, File).lower()
                Extension = FullPath.split('.')[-1]
                if Action == 1 and Extension in ExtensionScan:
                    Name = FullPath.split('\\')[-1]
                    print({FullPath: {"Name": Name, "Extension": Extension}})

This code works, but i want watcher on all hard disk not specific path

path_to_watch = "c:\"

I have an idea, call Watcher(drive="D:\\") with a specific drive by threading for all drives like below code :

Drives = ["C:\\", "D:\\", "E:\\"]

for i in Drives:
  Thread(target=Watcher, args=(i,).start()

but this solution is not good for processor performance

Finally, is there a way build in win32file for this solution or use my idea ?

Thanks all


Solution

  • def Watcher(_disk):
            ExtensionScan = ['exe', 'dll', 'vbs', 'com', 'jar']
            FILE_LIST_DIRECTORY = 0x0001
            path_to_watch = _disk
    ...
    
    for i in Drives:
         Thread(target=Watcher(i)