#!/usr/bin/env python3 import argparse import yaml import logging import logging.handlers from .core import arg_prompt from subprocess import check_output as cmd from subprocess import CalledProcessError class Account(): def __init__(self, args, config): self.__dict__.update(args) self.config = config self.logger = logging.getLogger(__name__) self.localpart = self.account.split('@')[0] # Create a formatted list, starting at 001. self.count = ("{0:03}".format(i) for i in range(1, self.total+1)) # Verify that the subject user exists. try: cmd([ config['google']['gam_command'], 'whatis', self.account ]) except CalledProcessError as e: self.logger.error(e.output, extra={'entity': self.account}) exit(2) def create_labels_and_filters(self): for i in self.count: if self.prefix: label = '{}-{}'.format(self.prefix, i) else: label = i # Generate the full alias (e.x. studymailbox+prefix-001) alias = '{}+{}@{}'.format( self.localpart, label, self.config['google']['domain'] ) try: cmd([ self.config['google']['gam_command'], 'user', self.account, 'label', label ]) cmd([ self.config['google']['gam_command'], 'user', self.account, 'filter', 'to', alias, 'label', label ]) except CalledProcessError as e: self.logger.error(e.output, extra={'entity': self.account}) def main(): helptext = '''examples: google-build-fitbitstudy -a awesomestudy -t 20 -p study1 google-build-fitbitstudy --account awesomestudy --toal 20 --prefix study1 ''' # Kick up an argument parser and assign values into the env object. parser = argparse.ArgumentParser( description='Creates labels and filters in a given Google account', epilog=helptext, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( '--account', '-a', help='The target account.', ) parser.add_argument( '--total', '-t', help='The total number of aliases to create.', default=50, type=int ) parser.add_argument( '--prefix', '-p', help='A prefix to append to aliases.' ) parser.add_argument( '--config', '-c', help='The CAK config to use', default='/etc/collab-admin-kit.yml' ) args = parser.parse_args() # Argument prompt fallback if not args.account: args.account = arg_prompt( 'Target existing shared account' ) args.total = arg_prompt( 'Number of alias labels to create. [50]', default=50 ) args.total = int(args.total) args.prefix = arg_prompt( '(optional) Prefix to assign to labels', default=None ) # Argument sanity check _required = ['account'] for r in _required: try: if isinstance(r, str): assert getattr(args, r) if isinstance(r, tuple): assert getattr(args, r[0]) or getattr(args, r[1]) except AssertionError: print('Missing required argument {}'.format(r)) # Open the CAK Config with open(args.config) as stream: config = yaml.load(stream, Loader=yaml.BaseLoader) # Get the root logger and set the debug level logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Create a syslog handler, set format, and associate. sh = logging.handlers.SysLogHandler( address='/dev/log', facility=config['general']['log_facility'] ) formatter = logging.Formatter(config['general']['log_format']) sh.setFormatter(formatter) logger.addHandler(sh) # Create a console handler, set format, and associate. ch = logging.StreamHandler() formatter = logging.Formatter( config['general']['console_format'], config['general']['date_format'] ) ch.setFormatter(formatter) logger.addHandler(ch) fba = Account(vars(args), config) fba.create_labels_and_filters() if __name__ == "__main__": main()