Guest User

Untitled

a guest
Dec 19th, 2015
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.30 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import subprocess
  4. import argparse
  5. import platform
  6. import sys
  7. import os
  8. import time
  9. import tempfile
  10.  
  11. distro, version, identity = platform.linux_distribution()
  12. date = time.strftime("%Y-%m-%d")
  13. os.environ['GZIP'] = '-6'
  14.  
  15. exclusions = [
  16. 'dev/*', 'media/*', 'mnt/*',
  17. 'proc/*', 'run/*', 'sys/*',
  18. 'tmp/*', 'Documents/*', 'Downloads/*',
  19. 'Music/*', 'Videos/*', 'photos'
  20. ]
  21.  
  22.  
  23. def clean_on_error(message, tarball):
  24. """Takes a string and the full tarball path. Displays the string as
  25. error message, and removes the incomplete tarball.
  26. """
  27. try:
  28. print(message, '\ncleaning ...')
  29. os.remove(tarball)
  30.  
  31. except OSError:
  32. pass
  33.  
  34.  
  35. def genpath(destination, parameters):
  36. """Takes the destination directory and a list of the elements which
  37. forms the tarball name, adds the name to the list of exclusions and
  38. returns the full tarball path.
  39. """
  40. tarball_name = "-".join(i for i in parameters if i is not None) + '.tar.gz'
  41. tarball_path = os.path.join(destination, tarball_name)
  42. exclusions.append(tarball_name)
  43.  
  44. return tarball_path
  45.  
  46.  
  47. def parse_cmd_line():
  48. """Function to parse script options and generate an help page."""
  49. parser = argparse.ArgumentParser(
  50. description="A script to create tarball backups of the entire system"
  51. )
  52.  
  53. parser.add_argument(
  54. 'destination',
  55. help = 'The backup destination directory',
  56. action = 'store',
  57. type = str
  58. )
  59.  
  60. parser.add_argument(
  61. '-l', '--level',
  62. help = 'Choose compression level (1-9). Default to 6',
  63. action = 'store',
  64. dest = 'level',
  65. type = int,
  66. metavar = ''
  67. )
  68.  
  69. parser.add_argument(
  70. '-c', '--compare',
  71. help = 'Compare tarball against filesystem',
  72. action = 'store_true'
  73. )
  74.  
  75. parser.add_argument(
  76. '-s', '--simulate',
  77. help = 'Simulate the tarball extraction',
  78. action = 'store_true'
  79. )
  80.  
  81. parser.add_argument(
  82. '-a', '--add',
  83. help = 'Append given string to the tarball name',
  84. dest = 'tag',
  85. metavar = ''
  86. )
  87.  
  88. return parser.parse_args()
  89.  
  90.  
  91. def main():
  92. args = parse_cmd_line()
  93.  
  94. if args.level in range(1,10): os.environ['GZIP'] = '-' + str(args.level)
  95. tarball = genpath(args.destination, [distro, version, args.tag, date])
  96.  
  97. # check that user is root and destination dir exists
  98.  
  99. if os.getuid() != 0:
  100. print("Error: you must be root to run this script")
  101. sys.exit(1)
  102.  
  103. if not os.path.isdir(args.destination):
  104. print("Error: destination directory does not exist")
  105. sys.exit(1)
  106.  
  107. # create temporary file
  108.  
  109. tmp = tempfile.NamedTemporaryFile(prefix='tarbackup', dir='/tmp')
  110. for i in exclusions:
  111. i = i + "\n"
  112. tmp.write(bytes(i, 'UTF-8'))
  113.  
  114. tmp.seek(0)
  115. tmp.read().decode()
  116.  
  117. tmp_file_path = os.path.join('/tmp', tmp.name)
  118.  
  119. try:
  120. print('Creating the tarball, please wait ...')
  121. subprocess.check_call(
  122. [
  123. 'tar', '--auto-compress', '--directory=/',
  124. '-X', tmp_file_path, '--xattrs',
  125. '--selinux', '--acls', '--check-links',
  126. '--numeric-owner', '--create', '-f',
  127. tarball, '.'
  128. ]
  129. )
  130.  
  131. if args.compare:
  132. print('Comparing tarball content against filesystem ...')
  133. subprocess.check_call(
  134. ['tar', '--directory=/', '--compare', '-f', tarball]
  135. )
  136.  
  137. if args.simulate:
  138. print('Simulating the tarball extraction ...')
  139. subprocess.check_call(
  140. ['tar', '--extract', '--to-stdout', '-f', tarball],
  141. stdout=open('/dev/null','w')
  142. )
  143.  
  144. except subprocess.CalledProcessError as error:
  145. print('tar exit status: ', error.returncode)
  146. clean_on_error('An error occurred!', tarball)
  147. sys.exit(1)
  148.  
  149. except KeyboardInterrupt:
  150. clean_on_error('Script interrupted!', tarball)
  151. sys.exit(1)
  152.  
  153. else:
  154. print('All done! have a nice day!')
  155.  
  156. finally:
  157. tmp.close()
  158.  
  159. if __name__ == '__main__':
  160. main()
Add Comment
Please, Sign In to add comment