Advertisement
Guest User

Windows network share sync

a guest
Mar 8th, 2013
959
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 KB | None | 0 0
  1. Main.py:
  2.  
  3. import win32file, win32con, time, sys, os, re, threading, FileSystemWatcher, shutil, hashlib
  4.  
  5. global WatchedPath
  6. WatchedPath = "Z:\\"
  7.  
  8. global changes
  9. changes = []
  10.  
  11. global processLocked
  12. processLocked = False
  13.  
  14. global datapath
  15. datapath = "D:\\DATA_test\\"
  16.  
  17. global blacklist
  18. blacklist = []
  19.  
  20. class Startup():
  21.     def __init__(self):
  22.         Main()
  23.    
  24.  
  25. class Main():
  26.     def __init__(self):
  27.         Main.watcherloop(self, WatchedPath)
  28.  
  29.                    
  30.     def watcherloop(self, path, index=0):
  31.         global processLocked
  32.         changes.append([])
  33.         while True:
  34.             changes[index] = FileSystemWatcher.FileSystemWatcher.windows_watch_path(self, path)
  35.             if len(changes[index]) > 0 and not processLocked:
  36.                 processLocked = True
  37.                 #print("Changes" + str(index) + ": " + str(changes[index][0]))
  38.                 Main.FileHandler(self, changes[index][0])
  39.                 del changes[index][0]
  40.                 processLocked = False
  41.            
  42.            
  43.            
  44.     def FileHandler(self, file):
  45.         # File:
  46.         # 0 = Path, 1 = File, 3 = Action
  47.         if str(file[1]).endswith(".bak"):
  48.             return
  49.         #print("Handling: " + str(file))
  50.         if file[2] == 1:
  51.             #file created
  52.             Main.getFile(self, file[0],file[1])
  53.         elif file[2] == 2:
  54.             #file deleted
  55.             Main.deleteFile(self, file[1])
  56.             print("Deleted " + str(file[1]))
  57.         elif file[2] == 3:
  58.             #file updated
  59.             Main.getFile(self, file[0],file[1])
  60.         elif file[2] == 4:
  61.             #renamed
  62.             pass
  63.         elif file[2] == 5:
  64.             #renamed
  65.             pass
  66.         else:
  67.             print("Unexpected FileEvent")
  68.        
  69.         return
  70.     def getFile(self, remotename, filename):
  71.         if os.path.isfile(os.path.join(datapath, filename)):
  72.             if Main.createmd5(self, os.path.join(remotename, filename)) == Main.createmd5(self, os.path.join(datapath, filename)):
  73.                 return
  74.            
  75.         try:
  76.             shutil.copyfile(os.path.join(remotename, filename), os.path.join(datapath, filename))
  77.             print("Downloaded " + str(filename))
  78.         except PermissionError:
  79.             print("Permission denied while copying " + str(remotename))
  80.         return
  81.    
  82.     def deleteFile(self, filename):
  83.         if os.path.isfile(os.path.join(datapath, str(filename))):
  84.             os.remove(os.path.join(datapath, str(filename)))
  85.         return
  86.    
  87.     def createmd5(self, filePath):
  88.         fh = open(filePath, "rb")
  89.         m = hashlib.md5()
  90.         while True:
  91.             data = fh.read(8192)
  92.             if not data:
  93.                 break
  94.             m.update(data)
  95.         return m.hexdigest()
  96.        
  97. if __name__ == "__main__":
  98.     Startup()
  99.  
  100.  
  101.  
  102. FileSystemWatcher.py:
  103.  
  104. import win32file, win32con
  105.  
  106. class FileSystemWatcher(object):
  107.     def windows_watch_path(self, watched_path):
  108.        
  109.            
  110.         ACTIONS = {
  111.                    1 : 1,#"Created",
  112.                    2 : 2,#"Deleted",
  113.                    3 : 3,#"Updated",
  114.                    4 : 4,#"RenamedFrom",
  115.                    5 : 5#"RenamedTo"
  116.                    }
  117.         # Thanks to Claudio Grondi for the correct set of numbers
  118.         FILE_LIST_DIRECTORY = 0x0001
  119.            
  120.         try:
  121.             hDir = win32file.CreateFile (
  122.                                          watched_path
  123.                                          , FILE_LIST_DIRECTORY
  124.                                          , win32con.FILE_SHARE_READ |
  125.                                          win32con.FILE_SHARE_WRITE |
  126.                                          win32con.FILE_SHARE_DELETE
  127.                                          , None
  128.                                          , win32con.OPEN_EXISTING
  129.                                          , win32con.FILE_FLAG_BACKUP_SEMANTICS
  130.                                          , None
  131.                                          )
  132.         except:
  133.             # either it does not exist by this time, or some other issue... blah.
  134.             # we'll just say "it 'changed' from 'some other expected state'"
  135.             return [[watched_path, '', ACTIONS[2]]]
  136.            
  137.         results = win32file.ReadDirectoryChangesW (
  138.                                                    hDir,
  139.                                                    1024,
  140.                                                    True,
  141.                                                    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
  142.                                                    win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
  143.                                                    win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
  144.                                                    win32con.FILE_NOTIFY_CHANGE_SIZE |
  145.                                                    win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
  146.                                                    win32con.FILE_NOTIFY_CHANGE_SECURITY,
  147.                                                    None,
  148.                                                    None
  149.                                                    )
  150.  
  151.         files_changed = []
  152.         for action, fn in results:
  153.             files_changed.append(
  154.                                  [
  155.                                   watched_path
  156.                                   , fn
  157.                                   , ACTIONS[action]
  158.                                   ]
  159.                                  )
  160.             # print fullfn, ACTIONS.get(action, "Unknown")
  161.             return files_changed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement