Commit c4143a87 authored by Rob Carleski's avatar Rob Carleski 🇮🇸
Browse files

Add argument prompting to remaining scripts.

* Also fix up some formattting stuff.
* Other things probably.
parent e4b36cbd
def arg_prompt(text, **kwargs):
while True:
r = input('{}: '.format(text))
if r:
return r
elif 'default' in kwargs.keys():
return kwargs['default']
...@@ -5,6 +5,7 @@ import yaml ...@@ -5,6 +5,7 @@ import yaml
import logging import logging
import logging.handlers import logging.handlers
from .core import arg_prompt
from subprocess import check_output as cmd from subprocess import check_output as cmd
from subprocess import CalledProcessError from subprocess import CalledProcessError
...@@ -162,14 +163,13 @@ def main(): ...@@ -162,14 +163,13 @@ def main():
'--name', '--name',
'-n', '-n',
help='The name to use for the discussion group.', help='The name to use for the discussion group.',
required=True
) )
parser.add_argument( parser.add_argument(
'--email', '--email',
'-e', '-e',
help='The email address to use for the discussion group.', help='The email address to use for the discussion group.',
) )
owners = parser.add_mutually_exclusive_group(required=True) owners = parser.add_mutually_exclusive_group()
owners.add_argument( owners.add_argument(
'--owners', '--owners',
'-o', '-o',
...@@ -208,6 +208,51 @@ def main(): ...@@ -208,6 +208,51 @@ def main():
) )
args = parser.parse_args() args = parser.parse_args()
# Argument prompt fallback
if not args.name:
args.name = arg_prompt(
'Group display name'
)
args.email = arg_prompt(
'(optional) Local part to be used for the group email address',
default=''
)
args.owners = arg_prompt(
'(option 1) Full email addresses of owners, separated by spaces',
default=''
).split(' ')
args.owners_file = arg_prompt(
'(option 2) Full file path to a list of owners',
default=None
)
args.members = arg_prompt(
'(option 1) Full email addresses of members, separated by spaces',
default=''
).split(' ')
args.members_file = arg_prompt(
'(option 2) The full file path to a list of members',
default=None
)
args.description = arg_prompt(
'(optional) Description to assign to the group',
default=''
)
# Argument sanity check
_required = [
'name',
('owners', 'owners_file'),
('members', 'members_file')
]
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 # Open the CAK Config
with open(args.config) as stream: with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader) config = yaml.load(stream, Loader=yaml.BaseLoader)
......
...@@ -6,6 +6,7 @@ import re ...@@ -6,6 +6,7 @@ import re
import string import string
import yaml import yaml
from .core import arg_prompt
from subprocess import check_output as cmd from subprocess import check_output as cmd
from subprocess import CalledProcessError from subprocess import CalledProcessError
from time import sleep from time import sleep
...@@ -163,14 +164,12 @@ def main(): ...@@ -163,14 +164,12 @@ def main():
'--name', '--name',
'-n', '-n',
help='The name to assign to the resource.', help='The name to assign to the resource.',
required=True
) )
parser.add_argument( parser.add_argument(
'--owners', '--owners',
'-o', '-o',
help='Users to give management access to.', help='Users to give management access to.',
nargs='+', nargs='+',
required=True
) )
parser.add_argument( parser.add_argument(
'--resource_type', '--resource_type',
...@@ -192,6 +191,35 @@ def main(): ...@@ -192,6 +191,35 @@ def main():
) )
args = parser.parse_args() args = parser.parse_args()
# Argument prompt fallback
if not args.name:
args.name = arg_prompt(
'Name to assign to the resource'
)
args.owners = arg_prompt(
'(optional) Resource owner uniqnames, separated by spaces',
default=''
).split(' ')
args.resource_type = arg_prompt(
'(optional) Resource type',
default=''
)
args.description = arg_prompt(
'(optional) Resource description',
default=''
)
# Argument sanity check
_required = ['name']
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 # Open the CAK Config
with open(args.config) as stream: with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader) config = yaml.load(stream, Loader=yaml.BaseLoader)
......
...@@ -11,6 +11,7 @@ import string ...@@ -11,6 +11,7 @@ import string
import yaml import yaml
from boxsdk.object.collaboration import CollaborationRole from boxsdk.object.collaboration import CollaborationRole
from .core import arg_prompt
from datetime import datetime from datetime import datetime
from datetime import timedelta from datetime import timedelta
from secrets import choice from secrets import choice
...@@ -22,15 +23,6 @@ from time import sleep ...@@ -22,15 +23,6 @@ from time import sleep
devnull = open(os.devnull, 'w') devnull = open(os.devnull, 'w')
def arg_prompt(text, **kwargs):
while True:
r = input(text)
if r:
return r
elif 'default' in kwargs.keys():
return kwargs['default']
class SharedAccount: class SharedAccount:
def __init__(self, args, config): def __init__(self, args, config):
...@@ -130,7 +122,7 @@ Accounts section of the M+Box support site. ...@@ -130,7 +122,7 @@ Accounts section of the M+Box support site.
_, _,
CollaborationRole.CO_OWNER CollaborationRole.CO_OWNER
) )
except boxsdk.exception.BoxAPIException as e: except boxsdk.exception.BoxAPIException:
self.logger.warning( self.logger.warning(
'Unable to add {} as Box collaborator'.format( 'Unable to add {} as Box collaborator'.format(
_ _
...@@ -535,41 +527,47 @@ def main(): ...@@ -535,41 +527,47 @@ def main():
# Interactive mode # Interactive mode
if not args.account: if not args.account:
args.account = arg_prompt( args.account = arg_prompt(
'Please enter the account name: ' 'Account name'
)
_owners = arg_prompt(
'(for new accounts) Please specify owners separated by spaces: ',
default=[]
) )
if isinstance(_owners, str): args.owners = arg_prompt(
args.owners = _owners.split(' ') '(for new accounts) List owners separated by spaces',
elif isinstance(_owners, list): default=''
args.owners = _owners ).split(' ')
args.first_name = arg_prompt( args.first_name = arg_prompt(
'(for new accounts) Please enter a first name to use: ', '(for new accounts) First name to use',
default='' default=''
) )
args.last_name = arg_prompt( args.last_name = arg_prompt(
'(for new accounts) Please enter a last name to use: ', '(for new accounts) Last name to use',
default='' default=''
) )
args.service = arg_prompt( args.service = arg_prompt(
'Which service should accounts be created for? ' 'Service(s) to create account(s) for'
'(google/box/both) [both]: ', '(google/box/both) [both]',
default='both' default='both'
).lower() ).lower()
print(args.service)
if args.service == 'box' or args.service == 'both': if args.service == 'box' or args.service == 'both':
_secure = arg_prompt( _secure = arg_prompt(
'Apply security settings to Box account: [y/N] ', 'Apply security settings to Box account [y/N]',
default='n' default='n'
).lower() ).lower()
args.secure = True if _secure == 'y' else False args.secure = True if _secure == 'y' else False
args.password = arg_prompt( args.password = arg_prompt(
'(for new accounts) Please enter a password to use: ', '(optional) Please enter a password to use',
default=None 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 # Open the CAK Config
with open(args.config) as stream: with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader) config = yaml.load(stream, Loader=yaml.BaseLoader)
......
...@@ -4,6 +4,7 @@ import yaml ...@@ -4,6 +4,7 @@ import yaml
import logging import logging
import logging.handlers import logging.handlers
from .core import arg_prompt
from subprocess import check_output as cmd from subprocess import check_output as cmd
from subprocess import CalledProcessError from subprocess import CalledProcessError
...@@ -83,7 +84,6 @@ def main(): ...@@ -83,7 +84,6 @@ def main():
'--account', '--account',
'-a', '-a',
help='The target account.', help='The target account.',
required=True
) )
parser.add_argument( parser.add_argument(
'--total', '--total',
...@@ -105,6 +105,31 @@ def main(): ...@@ -105,6 +105,31 @@ def main():
) )
args = parser.parse_args() 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.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 # Open the CAK Config
with open(args.config) as stream: with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader) config = yaml.load(stream, Loader=yaml.BaseLoader)
......
...@@ -7,8 +7,11 @@ import logging.handlers ...@@ -7,8 +7,11 @@ import logging.handlers
import mcommunity import mcommunity
import os import os
import re import re
import string
import yaml import yaml
from .core import arg_prompt
from secrets import choice
from subprocess import check_output as cmd from subprocess import check_output as cmd
from subprocess import CalledProcessError from subprocess import CalledProcessError
from subprocess import STDOUT from subprocess import STDOUT
...@@ -217,7 +220,8 @@ def main(): ...@@ -217,7 +220,8 @@ def main():
''' '''
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description='Resets the password in Google for an account.', description='Resets the password in Google and'
'kerberos for a shared account.',
epilog=helptext, epilog=helptext,
formatter_class=argparse.RawDescriptionHelpFormatter formatter_class=argparse.RawDescriptionHelpFormatter
) )
...@@ -225,13 +229,11 @@ def main(): ...@@ -225,13 +229,11 @@ def main():
'--account', '--account',
'-a', '-a',
help='The target account name.', help='The target account name.',
required=True
) )
parser.add_argument( parser.add_argument(
'--password', '--password',
'-p', '-p',
help='The new password to use.', help='The new password to use.',
required=True
) )
parser.add_argument( parser.add_argument(
'--config', '--config',
...@@ -241,6 +243,27 @@ def main(): ...@@ -241,6 +243,27 @@ def main():
) )
args = parser.parse_args() args = parser.parse_args()
# Argument prompt fallback
if not args.account:
args.account = arg_prompt(
'Target shared account to reset password for'
)
args.password = arg_prompt(
'(optional) Password to set',
default=''
)
# 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 # Open the CAK Config
with open(args.config) as stream: with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader) config = yaml.load(stream, Loader=yaml.BaseLoader)
...@@ -267,6 +290,10 @@ def main(): ...@@ -267,6 +290,10 @@ def main():
ch.setFormatter(formatter) ch.setFormatter(formatter)
logger.addHandler(ch) logger.addHandler(ch)
if not args.password:
pool = string.ascii_letters + string.digits + '!@#$%&*'
args.password = ''.join(choice(pool) for i in range(12))
sa = SharedAccount(vars(args), config) sa = SharedAccount(vars(args), config)
sa.check_mcommunity() sa.check_mcommunity()
sa.check_box() sa.check_box()
......
...@@ -6,6 +6,7 @@ import logging.handlers ...@@ -6,6 +6,7 @@ import logging.handlers
import os import os
import yaml import yaml
from .core import arg_prompt
from subprocess import CalledProcessError from subprocess import CalledProcessError
from subprocess import check_output as cmd from subprocess import check_output as cmd
from datetime import datetime from datetime import datetime
...@@ -265,7 +266,7 @@ class Sifter: ...@@ -265,7 +266,7 @@ class Sifter:
'gdirectory' 'gdirectory'
], stderr=devnull ], stderr=devnull
) )
except CalledProcessError as e: except CalledProcessError:
self.logger.error( self.logger.error(
'Unable to create report directory', 'Unable to create report directory',
extra={'entity': self.account} extra={'entity': self.account}
...@@ -286,7 +287,7 @@ class Sifter: ...@@ -286,7 +287,7 @@ class Sifter:
'convert' 'convert'
], stderr=devnull ], stderr=devnull
) )
except CalledProcessError as e: except CalledProcessError:
self.logger.error( self.logger.error(
'Error uploading {}'.format(log_file), 'Error uploading {}'.format(log_file),
extra={'entity': self.account} extra={'entity': self.account}
...@@ -310,7 +311,6 @@ def main(): ...@@ -310,7 +311,6 @@ def main():
'--account', '--account',
'-a', '-a',
help="The user to sift files for.", help="The user to sift files for.",
required=True
) )
parser.add_argument( parser.add_argument(
'--root_folder_id', '--root_folder_id',
...@@ -353,6 +353,39 @@ def main(): ...@@ -353,6 +353,39 @@ def main():
) )
args = parser.parse_args() args = parser.parse_args()
# Argment prompt fallback
if not args.account:
args.account = arg_prompt(
'Sifter target user'
)
args.root_folder_id = arg_prompt(
'(optional) Use this folder ID as root',
default='root'
)
args.omit_foders = arg_prompt(
'(optional) Omit folders with the following names',
default=''
).split(' ')
args.destination_account = arg_prompt(
'(optional) Upload reports to this account. (defaults to you)',
default=False
)
args.skip_upload = arg_prompt(
'(optional) Skip upload of reports [y/N]',
default='n'
).lower()
# 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 # Open the CAK Config
with open(args.config) as stream: with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader) config = yaml.load(stream, Loader=yaml.BaseLoader)
......
...@@ -4,6 +4,7 @@ import logging ...@@ -4,6 +4,7 @@ import logging
import logging.handlers import logging.handlers
import yaml import yaml
from .core import arg_prompt
from subprocess import check_output as cmd from subprocess import check_output as cmd
from subprocess import CalledProcessError from subprocess import CalledProcessError
...@@ -87,14 +88,12 @@ def main(): ...@@ -87,14 +88,12 @@ def main():
'--account', '--account',
'-a', '-a',
help="The user to check files for.", help="The user to check files for.",
required=True
) )
parser.add_argument( parser.add_argument(
'--omit_labels', '--omit_labels',
'-o', '-o',
help='A list of additional labels to omit from the report.', help='A list of additional labels to omit from the report.',
nargs='+', nargs='+',
required=False,
default=[] default=[]
) )
parser.add_argument( parser.add_argument(
...@@ -105,6 +104,27 @@ def main(): ...@@ -105,6 +104,27 @@ def main():
) )
args = parser.parse_args() args = parser.parse_args()
# Argument prompt fallback
if not args.account:
args.account = arg_prompt(
'Sifter target account'
)