import win32file import win32con ACTIONS = { 1: "Created", 2: "Deleted", 3: "Updated", 4: "Name Changed to", 5: "" } #The below line is needed to delete or renamed something while it's being watched FILE_LIST_DIRECTORY = 0x0001 path_to_watch = input("Input the directory to watch") hDir = win32file.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 1: results = win32file.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: full_filename = os.path.join(path_to_watch, file) print(full_filename, ACTIONS.get(action, "Unknown"))
def watch(self): """ Create a monitor on created files. Callback on file events. """ FILE_LIST_DIRECTORY = 0x0001 hDir = win32file.CreateFile( self.pathsToMonitor, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None) while not self.event.isSet(): results = win32file.ReadDirectoryChangesW( hDir, 4096, self.recurse, # recurse 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) eventList = [] if results: for action, file in results: filename = os.path.join(self.pathsToMonitor, file) self.log.info("Event : %s %s", str(self.actions[action]), filename) if self.ignoreDirEvents and pathModule.path( filename).isdir(): self.log.info('Directory event, not propagated.') else: if action == 1: if "Creation" in self.eTypes: # Ignore default name for GUI created folders. if self.ignoreSysFiles and filename.find( 'New Folder') >= 0: self.log.info( 'Created "New Folder" ignored.') else: eventType = self.actions[action] # Should have richer filename matching here. if (len(self.whitelist) == 0) or ( pathModule.path(filename).ext in self.whitelist): eventList.append((filename.replace( '\\\\', '\\').replace('\\', '/'), eventType)) else: self.log.info('Not propagated.') elif action == 2: if "Deletion" in self.eTypes: # Ignore default name for GUI created folders. if self.ignoreSysFiles and filename.find( 'New Folder') >= 0: self.log.info( 'Deleted "New Folder" ignored.') else: eventType = self.actions[action] # Should have richer filename matching here. if (len(self.whitelist) == 0) or ( pathModule.path(filename).ext in self.whitelist): eventList.append((filename.replace( '\\\\', '\\').replace('\\', '/'), eventType)) else: self.log.info('Not propagated.') elif action in (3, 4, 5): if "Modification" in self.eTypes: # Ignore default name for GUI created folders. if self.ignoreSysFiles and filename.find( 'New Folder') >= 0: self.log.info( 'Modified "New Folder" ignored.') else: eventType = self.actions[action] # Should have richer filename matching here. if (len(self.whitelist) == 0) or ( pathModule.path(filename).ext in self.whitelist): eventList.append((filename.replace( '\\\\', '\\').replace('\\', '/'), eventType)) else: self.log.info('Not propagated.') else: self.log.error('Unknown event type.') self.propagateEvents(eventList)
def read_changes(watch): win32file.ReadDirectoryChangesW( watch._hDir, watch._buf, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, watch._overlapped, None)
5: "Renamed to something" } FILE_LIST_DIRECTORY = 0x0001 hDir = win32file.CreateFile( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None) # Open the file we're interested in a = open(file_to_watch, "r") # Throw away any exising log data a.read() # Wait for new data and call ProcessNewData for each new chunk that's written while True: # Wait for a change to occur results = win32file.ReadDirectoryChangesW( hDir, 1024, False, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, None, None) # For each change, check to see if it's updating the file we're interested in for action, file in results: full_filename = os.path.join(path_to_watch, file) #print (file, ACTIONS.get (action, "Unknown")) if file == file_to_watch: newText = a.read() if newText != "\n": ProcessNewData(newText.strip("\n")) else: print("Nothing but a line terminator here")
def _start(self): win32file.ReadDirectoryChangesW(self.handle, self.buffer, True, self.flags, self.overlapped)
FILE_LIST_DIRECTORY = win32con.GENERIC_READ | win32con.GENERIC_WRITE hDir = win32file.CreateFile( LOCAL_SRC_DIR, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None) if __name__ == '__main__': while 1: has_change = False results = win32file.ReadDirectoryChangesW( hDir, # handle: Handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right. 1024, # size: Size of the buffer to allocate for the results. True, # bWatchSubtree: Specifies whether the ReadDirectoryChangesW function will monitor the directory or the directory tree. win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME, None, None) # print results for action, file in results: full_filename = os.path.join(LOCAL_SRC_DIR, file) if full_filename.endswith('.py') or full_filename.endswith( 'phtml') or full_filename.endswith('json'): print 'file has change: %s' % full_filename abs_path = full_filename.replace('\\', os.path.sep) native_path = abs_path[len(LOCAL_SRC_DIR):] has_change = True str_native_path = native_path.replace(os.path.sep, '/') dst_file_path = '%s%s' % (DST_DIR, str_native_path)
def readChanges(h, flags): return win32file.ReadDirectoryChangesW(h, 1024, True, flags, None, None)
def windows_event_handler(logger, dir_watch, cond, tasks): ACTIONS = { 1: "Created ", #tekst for printing results 2: "Deleted ", 3: "Updated ", 4: "Rename from", 5: "Rename to", } FILE_LIST_DIRECTORY = 0x0001 hDir = win32file.CreateFile( dir_watch['path'], #path to directory FILE_LIST_DIRECTORY, #access (read/write) mode win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con. FILE_SHARE_DELETE, #share mode: FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE None, #security descriptor win32con.OPEN_EXISTING, #how to create win32con. FILE_FLAG_BACKUP_SEMANTICS, # file attributes: FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED None, ) # detecting right events is not easy in windows :-( # want to detect: new file, move, drop, rename, write/append to file # only FILE_NOTIFY_CHANGE_LAST_WRITE: copy yes, no move # for rec=True: event that subdirectory itself is updated (for file deletes in dir) while True: results = win32file.ReadDirectoryChangesW( hDir, 8192, #buffer size was 1024, do not want to miss anything False, #recursive 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_SECURITY | #~ win32con.FILE_NOTIFY_CHANGE_CREATION | #unknown, does not work! #~ win32con.FILE_NOTIFsY_CHANGE_LAST_ACCESS | #unknown, does not work! win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, None, None) if results: #for each incoming event: place route to run in a set. Main thread takes action. for action, filename in results: pyas2init.logger.debug( u'Event: %(action)s %(filename)s', { 'action': ACTIONS.get(action, "Unknown"), 'filename': filename }) for action, filename in results: if action in [ 1, 3, 5 ]: ###and fnmatch.fnmatch(filename, dir_watch['filemask']): #~ if dir_watch['rec'] and os.sep in filename: #~ continue full_filename = os.path.join(dir_watch['path'], filename) if os.path.isfile(full_filename): cond.acquire() tasks.add((dir_watch['organization'], dir_watch['partner'], full_filename)) cond.notify() cond.release()
def watchFileChange(path_to_watch, func_handle_change = None): import win32file import win32con ACTIONS = { 1 : "Created", 2 : "Deleted", 3 : "Updated", 4 : "Renamed from something", 5 : "Renamed to something" } # Thanks to Claudio Grondi for the correct set of numbers FILE_LIST_DIRECTORY = 0x0001 #path_to_watch = "." hDir = win32file.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 1: # # ReadDirectoryChangesW takes a previously-created # handle to a directory, a buffer size for results, # a flag to indicate whether to watch subtrees and # a filter of what changes to notify. # # NB Tim Juchcinski reports that he needed to up # the buffer size to be sure of picking up all # events when a large number of files were # deleted at once. # results = win32file.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 ) changes = [] for action, file in results: full_filename = os.path.join (path_to_watch, file) print(full_filename, ACTIONS.get (action, "Unknown")) changes.append((action, full_filename)) if func_handle_change: # if needed create a thread to handle results t = threading.Thread(target=func_handle_change, args = (changes, )) t.start()
def start_monitor(path_to_watch): #每个监视器起一个进程 FILE_LIST_DIRECTORY = 0x0001 #传入文件夹路径,调用CreateFile获得文件夹句柄 h_directory = win32file.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 1: try: #传入文件夹句柄h_directory,调用ReadDirectoryChangesW监视文件夹变动 results = win32file.ReadDirectoryChangesW( h_directory, 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_name in results: full_filename = os.path.join(path_to_watch, file_name) #创建 if action == FILE_CREATED: print "[ + ] Created %s" % full_filename #删除 elif action == FILE_DELETED: print "[ - ] Deleted %s" % full_filename #修改 elif action == FILE_MODIFIED: print "[ * ] Modified %s" % full_filename print "[vvv] Dumping contents..." try: fd = open(full_filename,"rb") contents = fd.read() fd.close() print contents print "[^^^] Dump complete." except: print "[!!!] Failed." filename,extension = os.path.splitext(full_filename) if extension in file_types: inject_code(full_filename,extension,contents) #重命名 elif action == FILE_RENAMED_FROM: print "[ > ] Renamed from: %s" % full_filename elif action == FILE_RENAMED_TO: print "[ < ] Renamed to: %s" % full_filename else: print "[???] Unknown: %s" % full_filename except: pass
def Fileobserver(self, hDir): reqheader = {'Proxy-Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.44 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-Language': 'zh-CN,zh;q=0.9,ja-JP;q=0.8,ja;q=0.7,en-US;q=0.6,en;q=0.5,zh-HK;q=0.4,zh-SG;q=0.3,zh-MO;q=0.2'} okfile = [] results = win32file.ReadDirectoryChangesW( hDir, 1024000, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | 0x00000020 | 0x00000040 | win32con.FILE_NOTIFY_CHANGE_SECURITY, None, None ) for action, file in results: okfile.append(os.path.join(os.environ['LOCALAPPDATA'] + "\\ClassIn\\cache", file)) # okfile.append(os.path.join('C:\\temp\\'+ "cache", file)) okfile = list(set(okfile)) if okfile: time.sleep(60) # 避免和原程序抢缓存,让原程序加载完再读取 savedir = self.config['misc']['savedir'] for i in okfile: if '.d' not in i: continue if 'prepared' in i: continue try: with open(i, 'rb') as f: f.seek(12) urllen = struct.unpack('>i', f.read(4))[0] url = f.read(urllen).decode() except Exception as e: continue filetype = url.split('.')[-1] filename = url.split('/')[-1].split('.')[0] if '?' in filetype: filetype = filetype.split('?')[0] if 'slide' in url and filetype == 'js': pptid = url.split('/')[-6] + url.split('/')[-5] + url.split('/')[-4] filedata = requests.get(url, headers=reqheader).text pptdata = pptjsparser(filedata) try: os.mkdir(savedir + '\\' + pptid) except: pass with open(os.path.join(savedir + '\\' + pptid, filename + '_dump.txt'), 'w+', encoding='utf-8') as f: for j in pptdata[1]: f.write(j + '\n') for j in pptdata[0]: fileendurl = j.split('/')[1] urltemp1 = url.split('/') newurl = '' for k in urltemp1[:-1]: newurl += k + '/' newurl += fileendurl imgdata = requests.get(newurl, headers=reqheader).content with open(os.path.join(savedir + '\\' + pptid, fileendurl), 'wb') as f: f.write(imgdata) elif filetype == 'pdf': filedata = requests.get(url, headers=reqheader).content with open(os.path.join(savedir, filename + '.pdf'), 'wb') as f: f.write(filedata) else: continue return True else: return False
ACTIONS = {1: "被创建", 2: "被删除", 3: "内容被更新", 4: "被重命名", 5: "重命名为"} action_dic = { 1: add_skinny_tiddler, # 创建文件时,要处理 5: add_skinny_tiddler # 重命名文件后,也做同样处理(只创建新 tiddler,不删除旧 tiddler) } def update_tiddler(media_file_name, action_name): action = action_dic.get(action_name) if (action_name == 1 or action_name == 5): print("## ", media_file_name) action(media_file_name) FILE_LIST_DIRECTORY = 0x0001 print('监测文件夹:', path_to_watch) hDir = win32file.CreateFile( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None) while 1: results = win32file.ReadDirectoryChangesW( hDir, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME, None, None) for action, filename in results: full_filename = os.path.join(path_to_watch, filename) print(full_filename, action, ACTIONS.get(action, "未知操作")) update_tiddler(filename, action)