Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.38 KB | None | 0 0
  1. # Script to open programs, make backups, and push to git every 1hr when ever changes are made
  2. # Setup git & backup folder to push to remote or self-hosted network to secure backups outside of local to protect if hardware failure occurs
  3.  
  4. # Created 03.14.2019
  5. # Updated 03.16.2019
  6.  
  7. """ Example of txt file
  8.  
  9. --- Program to open ---
  10. C:\Program Files\...\SomeIDEProg.exe
  11. --- Location to scan for periodic backups ---
  12. D:\Projects\...\SomeFolder
  13. --- Location to place the backups ---
  14. E:\Backup
  15.  
  16. """
  17.  
  18. fileName = "directoryToScan.txt"
  19. fileExtToIgnore = ["~", ".TMP"]
  20. # fiesExtToSave = [".cs"]
  21. # Set max file size to backup
  22. maxFileSize = 1000000
  23.  
  24. import errno
  25. import shutil
  26. import os
  27. import sys
  28. import sched
  29. import time, datetime
  30. import git
  31. import subprocess
  32. import threading
  33. from watchdog.observers import Observer
  34. from watchdog.events import FileSystemEventHandler
  35.  
  36. def opentext(name, parameter):
  37. content2 = []
  38. file = open(name, parameter)
  39. content = file.readlines()
  40. file.close()
  41. for file in content:
  42. file = file.split("\n")
  43. content2.append(file[0])
  44. return content2
  45.  
  46. def openProgram(file):
  47. subprocess.Popen([file])
  48.  
  49. def scanForChanges(scanFolder, saveFolder):
  50.  
  51. class Watcher:
  52. DIRECTORY_TO_WATCH = scanFolder
  53.  
  54. def __init__(self):
  55. self.observer = Observer()
  56.  
  57. def run(self, startingScan = True):
  58. event_handler = Handler()
  59. self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
  60. self.observer.start()
  61.  
  62. if (startingScan == True):
  63. print("Scanning for file changes at: " + str(scanFolder))
  64. startingScan = False
  65.  
  66. try:
  67. while True:
  68. time.sleep(1)
  69. except:
  70. self.observer.stop()
  71. print("Error")
  72.  
  73. self.observer.join()
  74.  
  75.  
  76. class Handler(FileSystemEventHandler):
  77. @staticmethod
  78. def on_any_event(event):
  79.  
  80. if event.is_directory:
  81. return None
  82.  
  83. elif event.event_type == 'created':
  84. # Take any action here when a file is first created.
  85. # print("Received created event - " + str(event.src_path))
  86. file = str(event.src_path)
  87. try:
  88. copyfile(scanFolder, saveFolder, file)
  89. except:
  90. print("Could not backup: " + file)
  91.  
  92. elif event.event_type == 'modified':
  93. # Taken any action here when a file is modified.
  94. # print("Received modified event - " + str(event.src_path))
  95. file = str(event.src_path)
  96. try:
  97. copyfile(scanFolder, saveFolder, file)
  98. except:
  99. print("Could not backup: " + file)
  100.  
  101. def copyfile(scanFolder, saveFolder, file):
  102. skipfile = False
  103.  
  104. t = datetime.datetime.now()
  105. file = str(file)
  106. fileName = file.replace(scanFolder,'')
  107. root, ext = os.path.splitext(fileName)
  108.  
  109. # Checek if file is in the list of extentions to be ignored
  110. for ignore in fileExtToIgnore:
  111.  
  112. c1 = ignore
  113. c2 = ext[-1:]
  114.  
  115. if (str(c1).endswith(str(ext))) or (str(c1) == str(c2)):
  116. skipfile = True
  117. # print("File skipped: " + str(fileName))
  118. break
  119.  
  120. # Check file size if it isn't ignored
  121. if (skipfile == False):
  122. fileSize = os.path.getsize(scanFolder + fileName)
  123. if (maxFileSize < fileSize):
  124. print("File size is too large: " + str(file))
  125. skipfile = True
  126.  
  127. # Backup file
  128. if (skipfile == False):
  129. timeStamp = " (" + str(t.year) + "-" + str(t.month) + "-" + str(t.day) + " " + str(t.hour) + "hr" + str(t.minute) + "m)"
  130. dst = saveFolder + str(root) + timeStamp + str(ext)
  131. folder = os.path.dirname(os.path.realpath(dst))
  132. if not os.path.exists(folder):
  133. os.makedirs(folder)
  134. shutil.copy2(file, dst)
  135. print("Created backup file: " + dst)
  136.  
  137. # Run git every 1hr
  138. def runProc1():
  139. s = sched.scheduler(time.time, time.sleep)
  140.  
  141. def runGit(sched):
  142. try:
  143. repo = git.Repo(saveFolder)
  144. repo.git.add(".")
  145. t = datetime.datetime.today()
  146. commitMsg = str(datetime.date.today()) + " @ " + str(t.hour) + ":" + str(t.minute)
  147. repo.git.commit('-m', commitMsg)
  148. repo.git.push()
  149. print("\nSuccessfully backed up - backup files\n")
  150. # 60 sec * 60 min = 3600
  151. s.enter(3600, 1, runGit, (sched,))
  152. except Exception as e:
  153. print("\nCould not backed up - backup files\n\n" + str(e) + "\n")
  154. s.enter(3600, 1, runGit, (sched,))
  155.  
  156. s.enter(1, 1, runGit, (s,))
  157. s.run()
  158.  
  159. # Scan for changes to backup
  160. def runProc2():
  161. w = Watcher()
  162. w.run()
  163.  
  164. if __name__ == '__main__':
  165. p1 = threading.Thread(target=runProc1)
  166. p2 = threading.Thread(target=runProc2)
  167.  
  168. p1.start()
  169. p2.start()
  170.  
  171.  
  172. def main():
  173. location = opentext(fileName, "r")
  174. print("Opening: " + location[1])
  175. openProgram(location[1])
  176. scanForChanges(location[3], location[5])
  177.  
  178. if __name__ == "__main__":
  179. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement