dip

old school recipes for janitorial snafu.
git clone git://git.ricketyspace.net/dip.git
Log | Files | Refs

gnupg-backup (3734B)


      1 #!/usr/bin/env python
      2 #
      3 # License: CC0-1.0
      4 #
      5 
      6 import os
      7 import shlex
      8 import sys
      9 
     10 from argparse import ArgumentParser
     11 from hashlib import sha256
     12 from os import path
     13 from shutil import rmtree
     14 from subprocess import call
     15 
     16 GPG = 'gpg'
     17 
     18 OPT_EXPORT = '-a --export'
     19 OPT_EXPORT_SEC = '-a --export-secret-keys'
     20 OPT_EXPORT_TRUST = '--export-ownertrust'
     21 
     22 OPT_SYM_ENCRYPT = "--symmetric"
     23 OPT_GPG_OUT = "--output"
     24 
     25 TAR = 'tar'
     26 OPT_TAR_CRT = 'cvzf'
     27 OUT_TAR_SUFFIX = '.tar.gz'
     28 
     29 DIR_PREFIX = 'gnupg-'
     30 
     31 OUT_PUB = 'pub.key'
     32 OUT_SEC = 'sec.key'
     33 OUT_TRUST = 'trust.gpg'
     34 
     35 def tar_it(f):
     36     """
     37     Creates a compressed tar ball of `f` at path.dirname(directory).
     38 
     39     Returns the path of the compress tar ball.
     40     """
     41     tar_ball = path.join(path.dirname(f),
     42                          "%s%s" % (path.basename(f),
     43                                    OUT_TAR_SUFFIX))
     44 
     45     print(("creating tar ball {}...".format(tar_ball)))
     46     call(shlex.split("%s %s %s %s" % (TAR, OPT_TAR_CRT, tar_ball,
     47                                       f)))
     48 
     49     return tar_ball
     50 
     51 
     52 def encrypt_it(f):
     53     """
     54     Encrypts file `f`.
     55     """
     56     blob = sha256(f.encode()).hexdigest()
     57     blob_path = path.join(path.dirname(f), blob)
     58 
     59     print(("blobbing {} to {}".format(f, blob_path)))
     60     call(shlex.split("%s %s %s %s %s" % (GPG, OPT_GPG_OUT, blob_path,
     61                                    OPT_SYM_ENCRYPT, f)))
     62 
     63 
     64 def gnupg_export(fpr, directory, encrypt=False):
     65     """Export gnupg data connected with fingerprint `fpr` to `directory`.
     66 
     67     This function will create directory call `gnupg-fpr` inside
     68     `directory` and export gnupg data connected with fingerprint `fpr`
     69     to 3 seperate files under `gnupg-fpr`.
     70 
     71     If `encrypt` is True, then encrypt the whole export.
     72 
     73     """
     74 
     75     # Remove spaces from fingerprint
     76     fpr = fpr.replace(' ', '')
     77 
     78     # First make the `gnupg-fpr` directory.
     79     try:
     80         export_dir = path.join(directory,
     81                                     "%s%s" % (DIR_PREFIX, fpr))
     82         os.mkdir(export_dir)
     83     except OSError:
     84         print(("Looks like {} already exists".format(export_dir)))
     85 
     86     # Export public key.
     87     pub_key = path.join(export_dir, OUT_PUB)
     88 
     89     print(("writing public key to {}".format(pub_key)))
     90     with open(pub_key, 'w') as out:
     91         call(shlex.split("%s %s %s" % (GPG, OPT_EXPORT, fpr)),
     92              stdout=out)
     93 
     94     # Export secret key.
     95     sec_key = path.join(export_dir, OUT_SEC)
     96 
     97     print(("writing secret key to {}".format(sec_key)))
     98     with open(sec_key, 'w') as out:
     99         call(shlex.split("%s %s %s" % (GPG, OPT_EXPORT_SEC, fpr)),
    100              stdout=out)
    101 
    102     # Export trust.
    103     trust = path.join(export_dir, OUT_TRUST)
    104 
    105     print(("writing owner trust to {}".format(trust)))
    106     with open(trust, 'w') as out:
    107         call(shlex.split("%s %s" % (GPG, OPT_EXPORT_TRUST)),
    108              stdout=out)
    109 
    110     # Create a tar ball of the export_dir.
    111     tar_ball = tar_it(export_dir)
    112 
    113     # If asked for, encrypt the tar ball.
    114     if encrypt:
    115         encrypt_it(tar_ball)
    116         os.remove(tar_ball)
    117 
    118     # Clean up.
    119     rmtree(export_dir)
    120 
    121 
    122 if __name__ == "__main__":
    123     parser = ArgumentParser()
    124     group = parser.add_argument_group('group')
    125     group.add_argument('fpr',
    126                         help="fingerprint of key to export.")
    127     group.add_argument('directory',
    128                         help="directory to export to.")
    129     group.add_argument('-e', '--encrypt', action="store_true",
    130                        help="encrypt the export.")
    131     args = parser.parse_args()
    132 
    133     directory = path.expanduser(args.directory)
    134     if path.exists(directory):
    135         gnupg_export(args.fpr, directory, args.encrypt)
    136     else:
    137         print(("{} does not exist. Exiting...".format(directory)))
    138         sys.exit(1)