使用python监控windows文件夹,并通过微信发送到手机上

到新单位,有个任务,每天要巡查备份文件是否正常生成。服务器清单上170多台服务器,比较重要的有30多台。每天如果手工登陆去查看的工作量,就要花费快2个小时。于是自己用python写了一个文件夹监控,监控文件的产生日期、文件名、文件大小等信息,实时推送到手机微信上。

运行环境

Python3.7
安装win32file模块

1
pip install pypiwin32

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
# coding=utf-8
import os
import sys
import time
import win32file
import win32con
import subprocess

def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime('%Y-%m-%d/%H:%M:%S',timeStruct)


ACTIONS = {
1: "Created",
2: "Deleted",
3: "Updated",
4: "Renamed from something",
5: "Renamed to something"
}


temptask = []
FILE_LIST_DIRECTORY = 0x0001

path_to_watch = 'c:/test'
print ('Watching changes in', 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 |
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, filename in results:
full_filename = os.path.join(path_to_watch, filename)
print (full_filename, ACTIONS.get(action, "Unknown"))
if ACTIONS.get(action, "Unknown") == "Deleted":
message = full_filename, ACTIONS.get(action, "Unknown")
message1 = str(message)
task = message1.split(" ")
subprocess.call(['python','weixin.py',task])
else:
try:
filesize = os.path.getsize(full_filename)
filesize = filesize/float(1024*1024)
filesize = str(round(filesize,2)) + "MB"
filetime = os.path.getctime(full_filename)
tt = TimeStampToTime(filetime)
message = tt,full_filename, ACTIONS.get(action, "Unknown"),filesize
message1 = str(message)
task = message1.split(" ")
except Exception as e:
continue
# message = full_filename, ACTIONS.get(action, "Unknown")
# message1 = str(message)
# task = message1.split(" ")
# subprocess.call(['python','weixin.py',task])
finally:
if task != temptask:
subprocess.call(['python','weixin.py',task])
temptask = task

实现功能

监控C盘下的test目录,该目录如果产生任何文件变化,(不管是更名、编辑、删除)都会将变化文件的生成时间、文件名、文件大小等信息,推送到我的手机上了。这样不用花时间被动的去做巡检任务了,还有变更历史记史、实时了解,非常方便!


-------------本文结束 感谢您的阅读-------------
-------------如果觉得这篇文章不错,可以请作者喝杯咖啡!-------------