#!/usr/bin/env python # -*- coding: utf-8 -*- import json import os import subprocess import sys def main(): if (len(sys.argv) != 2): sys.exit('Invalid parameter. Usage: {0} \n'.format( sys.argv[0])) cstm_error = '' try: cstm_error = 'Could not open config (~/.cmount.json)' with open(os.path.expanduser('~/.cmount.json')) as fp: config_dict = json.load(fp) cstm_error = 'Invalid / nonexistent mapping: {0}'.format(sys.argv[1]) data = config_dict[sys.argv[1]] if data.get('type') == 'lvm': if not isinstance(data.get('pv_sources'), dict): cstm_error = 'Invalid config for lvm-type' raise Exception() cstm_error = 'umount error' subprocess.check_call(['/bin/umount', data['device']]) cstm_error = 'lvchange error' subprocess.check_call(['/sbin/lvchange', '-a', 'n', data['device']]) cstm_error = 'vgexport error' subprocess.check_call(['/sbin/vgexport', data['device'].split('/')[2]]) cstm_error = 'pv_sources error' for mapper_name in data['pv_sources'].values(): subprocess.check_call(['/sbin/cryptsetup', 'luksClose', mapper_name]) else: subprocess.check_call(['/bin/umount', '/dev/mapper/' + data['mapper_name']]) subprocess.check_call(['/sbin/cryptsetup', 'luksClose', data['mapper_name']]) if data.get('type') == 'efile': cstm_error = 'Unable to destroy loop device' loop_device = subprocess.check_output(['/usr/sbin/losetup', '--associated', data['device']]) loop_device = loop_device.split(':')[0] subprocess.check_call(['/usr/sbin/losetup', '-d', loop_device]) except subprocess.CalledProcessError as e: print('Execution error: {0}\n'.format(e), file=sys.stderr, flush=True) except Exception: print('Error: {0}\n'.format(cstm_error), file=sys.stderr, flush=True) if __name__ == '__main__': main()