backup.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """This script zip TEMPORARY folders and files (according to an regex pattern)
  2. and upload to Amazon S3 service (AND DELETE FOLDERS/FILES AFTER BACKUP)."""
  3. import os
  4. import re
  5. import zipfile
  6. import json
  7. import time
  8. import shutil
  9. import boto3
  10. # Configuration file
  11. with open('config.json') as json_data_file:
  12. CONFIG = json.load(json_data_file)
  13. def zipd(directory, path):
  14. """Zip entire directory and DELETE it."""
  15. path = ('' if path == '.' else path) + directory
  16. filename = path + '.zip'
  17. zipf = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED)
  18. for root, dirs, files in os.walk(path):
  19. for file in files:
  20. zipf.write(os.path.join(root, file))
  21. zipf.close()
  22. shutil.rmtree(path)
  23. return filename
  24. def backupd(path, pattern, prefix=''):
  25. """Backup folders based on given path, regex pattern and a optional prefix
  26. for filename (backup file)."""
  27. for directories in os.walk(path, topdown=True):
  28. for directory in directories[1]:
  29. folder_name = re.search(pattern, directory)
  30. if folder_name is not None:
  31. backupfile = zipd(directory, path)
  32. upload(backupfile, prefix + directory + '.zip')
  33. # Delete backup file after uploaded (zip)
  34. os.remove(backupfile)
  35. def backupf(path, pattern, backup_filename):
  36. """Backup files based on regex pattern and DELETE it"""
  37. temppath = ('' if path == '.' else path)
  38. backupfile = temppath + backup_filename + '.zip'
  39. zipf = zipfile.ZipFile(backupfile, 'w', zipfile.ZIP_DEFLATED)
  40. for root, dirs, files in os.walk(path, topdown=True):
  41. for file in files:
  42. filename = re.search(pattern, file)
  43. if filename is not None:
  44. zipf.write(os.path.join(root, file))
  45. os.remove(temppath + file)
  46. zipf.close()
  47. upload(backupfile, backup_filename + '.zip')
  48. # Delete backup file after uploaded (zip)
  49. os.remove(backupfile)
  50. def upload(path, key):
  51. """Upload file to Amazon S3"""
  52. s3_client = boto3.resource(
  53. 's3',
  54. aws_access_key_id=CONFIG['aws']['s3']['access-key'],
  55. aws_secret_access_key=CONFIG['aws']['s3']['secret-access-key']
  56. )
  57. s3_client.meta.client.upload_file(path, CONFIG['aws']['s3']['bucket'],
  58. time.strftime("%Y/%m/%d/") + key)
  59. # Folder name examples: Backup_Relatorios_2110_2017_00_00,
  60. # Backup_Imagens_2110_2017_00_00. File Examples: Backup_BACKUPLOG_0611_2017_00_00.log
  61. # backupd('.', '_(.*)_(\\d{2})(\\d{2})_(\\d{4})_(\\d{2})_(\\d{2})')
  62. # backupf('.', '_(.*)_' + time.strftime("%d%m") + '_(\\d{4})_(\\d{2})_(\\d{2})',
  63. # 'BACKUPLOG_' + time.strftime("%d%m_%Y"))