Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import subprocess
- import argparse
- import platform
- import sys
- import os
- import time
- import tempfile
- distro, version, identity = platform.linux_distribution()
- date = time.strftime("%Y-%m-%d")
- os.environ['GZIP'] = '-6'
- exclusions = [
- 'dev/*', 'media/*', 'mnt/*',
- 'proc/*', 'run/*', 'sys/*',
- 'tmp/*', 'Documents/*', 'Downloads/*',
- 'Music/*', 'Videos/*', 'photos'
- ]
- def clean_on_error(message, tarball):
- """Takes a string and the full tarball path. Displays the string as
- error message, and removes the incomplete tarball.
- """
- try:
- print(message, '\ncleaning ...')
- os.remove(tarball)
- except OSError:
- pass
- def genpath(destination, parameters):
- """Takes the destination directory and a list of the elements which
- forms the tarball name, adds the name to the list of exclusions and
- returns the full tarball path.
- """
- tarball_name = "-".join(i for i in parameters if i is not None) + '.tar.gz'
- tarball_path = os.path.join(destination, tarball_name)
- exclusions.append(tarball_name)
- return tarball_path
- def parse_cmd_line():
- """Function to parse script options and generate an help page."""
- parser = argparse.ArgumentParser(
- description="A script to create tarball backups of the entire system"
- )
- parser.add_argument(
- 'destination',
- help = 'The backup destination directory',
- action = 'store',
- type = str
- )
- parser.add_argument(
- '-l', '--level',
- help = 'Choose compression level (1-9). Default to 6',
- action = 'store',
- dest = 'level',
- type = int,
- metavar = ''
- )
- parser.add_argument(
- '-c', '--compare',
- help = 'Compare tarball against filesystem',
- action = 'store_true'
- )
- parser.add_argument(
- '-s', '--simulate',
- help = 'Simulate the tarball extraction',
- action = 'store_true'
- )
- parser.add_argument(
- '-a', '--add',
- help = 'Append given string to the tarball name',
- dest = 'tag',
- metavar = ''
- )
- return parser.parse_args()
- def main():
- args = parse_cmd_line()
- if args.level in range(1,10): os.environ['GZIP'] = '-' + str(args.level)
- tarball = genpath(args.destination, [distro, version, args.tag, date])
- # check that user is root and destination dir exists
- if os.getuid() != 0:
- print("Error: you must be root to run this script")
- sys.exit(1)
- if not os.path.isdir(args.destination):
- print("Error: destination directory does not exist")
- sys.exit(1)
- # create temporary file
- tmp = tempfile.NamedTemporaryFile(prefix='tarbackup', dir='/tmp')
- for i in exclusions:
- i = i + "\n"
- tmp.write(bytes(i, 'UTF-8'))
- tmp.seek(0)
- tmp.read().decode()
- tmp_file_path = os.path.join('/tmp', tmp.name)
- try:
- print('Creating the tarball, please wait ...')
- subprocess.check_call(
- [
- 'tar', '--auto-compress', '--directory=/',
- '-X', tmp_file_path, '--xattrs',
- '--selinux', '--acls', '--check-links',
- '--numeric-owner', '--create', '-f',
- tarball, '.'
- ]
- )
- if args.compare:
- print('Comparing tarball content against filesystem ...')
- subprocess.check_call(
- ['tar', '--directory=/', '--compare', '-f', tarball]
- )
- if args.simulate:
- print('Simulating the tarball extraction ...')
- subprocess.check_call(
- ['tar', '--extract', '--to-stdout', '-f', tarball],
- stdout=open('/dev/null','w')
- )
- except subprocess.CalledProcessError as error:
- print('tar exit status: ', error.returncode)
- clean_on_error('An error occurred!', tarball)
- sys.exit(1)
- except KeyboardInterrupt:
- clean_on_error('Script interrupted!', tarball)
- sys.exit(1)
- else:
- print('All done! have a nice day!')
- finally:
- tmp.close()
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment