用Python写一段代码,实时监测哪个软件读写了C盘和D盘的文件。并在图形化界面展示出来。(时间、进程名、操作盘符、具体操作(删除,修改或新建))
时间: 2023-06-27 16:05:58 浏览: 41
这个任务需要用到Python的Win32 API来监测文件系统操作,并且需要使用GUI库来创建窗口。下面是一个简单的示例代码:
```python
import win32file
import win32con
import tkinter as tk
class FileMonitor:
def __init__(self, root):
self.root = root
self.text = tk.Text(root)
self.text.pack(fill='both', expand=True)
self.handles = {}
self.start_monitor()
def start_monitor(self):
drives = ['C:\\', 'D:\\']
flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE
for drive in drives:
handle = win32file.FindFirstChangeNotification(drive, False, flags)
self.handles[drive] = handle
self.text.insert('end', f'Start monitoring {drive}\n')
self.root.after(1000, self.check_changes)
def check_changes(self):
for drive, handle in self.handles.items():
result = win32file.WaitForSingleObject(handle, 0)
if result == win32con.WAIT_OBJECT_0:
try:
data = win32file.ReadDirectoryChangesW(handle, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, None, None)
for action, file_name in data:
if action == 1:
action_str = 'Created'
elif action == 2:
action_str = 'Deleted'
elif action == 3:
action_str = 'Updated'
else:
action_str = 'Unknown'
self.text.insert('end', f'{drive} {file_name} {action_str}\n')
self.text.see('end')
finally:
win32file.FindNextChangeNotification(handle)
self.root.after(1000, self.check_changes)
root = tk.Tk()
root.geometry('500x300')
monitor = FileMonitor(root)
root.mainloop()
```
这个代码使用了Win32 API来监测C盘和D盘的文件变化,并且在GUI窗口中展示出来。具体实现过程是:首先使用`win32file.FindFirstChangeNotification()`函数创建一个监测句柄,然后使用`win32file.WaitForSingleObject()`函数等待文件变化,如果有变化就使用`win32file.ReadDirectoryChangesW()`函数读取变化的内容,然后在GUI窗口中展示出来。这个代码只是一个简单的示例,实际应用中可能需要对不同的操作进行不同的处理。