Add info printer command/ChromePolicy cleanup (#1337)

* Add info printer command

* ChromePolicy cleanup

Make update chromepolicy orgunit default to / like delete and print
Add `filter <String>` to print chromeschema
Make update_policy code to set additionalTargetKeys consistent with delete_policy

I left verb at print for chromepolicy/chromeschema

* When printing schemasa, use ":" instead of " - "

* Fix print policy indentation

* Chrome policy cleanup

orgunit must be specified
Use verb show, add verb print later

* Recognize all ou forms to exit from schema mode

* Don't assign multiple variables on same line
This commit is contained in:
Ross Scroggs
2021-03-19 09:46:07 -07:00
committed by GitHub
parent a65635365e
commit 6f2ebf8d2d
4 changed files with 66 additions and 37 deletions

View File

@@ -147,6 +147,7 @@ If an item contains spaces, it should be surrounded by ".
<AccessToken> ::= <String> <AccessToken> ::= <String>
<ACLScope> ::= [user:]<EmailAddress>|group:<EmailAddress>|domain[:<DomainName>]|default <ACLScope> ::= [user:]<EmailAddress>|group:<EmailAddress>|domain[:<DomainName>]|default
<APIScopeURL> ::= <String> <APIScopeURL> ::= <String>
<APPID> ::= <String>
<ASPID> ::= <String> <ASPID> ::= <String>
<AssetTag> ::= <String> <AssetTag> ::= <String>
<BrowserTokenPermanentID> ::= <String> <BrowserTokenPermanentID> ::= <String>
@@ -1230,10 +1231,10 @@ The listlimit <Number> argument limits the number of recent users, time ranges a
The start <Date> and end <Date> arguments filter the time ranges. The start <Date> and end <Date> arguments filter the time ranges.
Delimiter defaults to comma. Delimiter defaults to comma.
gam delete chromepolicy <SchemaName>+ [ou|orgunit <OrgUnitItem>] [(printerid <PrinterID>)|(appid <AppID>)] gam delete chromepolicy <SchemaName>+ ou|org|orgunit <OrgUnitItem> [(printerid <PrinterID>)|(appid <AppID>)]
gam update chromepolicy (<SchemaName> (<Field> <Value>)+)+ ou|orgunit <OrgUnitItem> [(printerid <PrinterID>)|(appid <AppID>)] gam update chromepolicy (<SchemaName> (<Field> <Value>)+)+ ou|org|orgunit <OrgUnitItem> [(printerid <PrinterID>)|(appid <AppID>)]
gam print chromepolicy [ou|orgunit <OrgUnitItem>] [(printerid <PrinterID>)|(appid <AppID>)] gam show chromepolicy ou|org|orgunit <OrgUnitItem> [(printerid <PrinterID>)|(appid <AppID>)]
gam print chromeschema gam show chromeschema [filter <String>]
<DeviceID> ::= devices/<String> <DeviceID> ::= devices/<String>
<DeviceType> ::= android|chrome_os|google_sync|ios|linux|mac_os|windows <DeviceType> ::= android|chrome_os|google_sync|ios|linux|mac_os|windows
@@ -1290,6 +1291,7 @@ gam create printer <PrinterAttribute>+
gam update printer <PrinterID> <PrinterAttribute>+ gam update printer <PrinterID> <PrinterAttribute>+
gam delete printer <PrinterIDList>|(file <FileName>)|(csvfile <FileName>:<FieldName>) gam delete printer <PrinterIDList>|(file <FileName>)|(csvfile <FileName>:<FieldName>)
gam info printer <PrinterID>
gam print printers [todrive] [filter <String>] gam print printers [todrive] [filter <String>]
gam print printermodels [todrive] [filter <String>] gam print printermodels [todrive] [filter <String>]

View File

@@ -11295,6 +11295,8 @@ def ProcessGAMCommand(args):
gapi_directory_domainaliases.info() gapi_directory_domainaliases.info()
elif argument in ['resoldcustomer', 'resellercustomer']: elif argument in ['resoldcustomer', 'resellercustomer']:
doGetResoldCustomer() doGetResoldCustomer()
elif argument in ['printer']:
gapi_directory_printers.info()
elif argument in [ elif argument in [
'resoldsubscription', 'resoldsubscriptions', 'resoldsubscription', 'resoldsubscriptions',
'resellersubscription', 'resellersubscriptions' 'resellersubscription', 'resellersubscriptions'
@@ -11493,10 +11495,6 @@ def ProcessGAMCommand(args):
gapi_directory_printers.print_models() gapi_directory_printers.print_models()
elif argument in ['printers']: elif argument in ['printers']:
gapi_directory_printers.print_() gapi_directory_printers.print_()
elif argument == 'chromeschema':
gapi_chromepolicy.print_schemas()
elif argument == 'chromepolicy':
gapi_chromepolicy.print_policies()
else: else:
controlflow.invalid_argument_exit(argument, 'gam print') controlflow.invalid_argument_exit(argument, 'gam print')
sys.exit(0) sys.exit(0)
@@ -11514,6 +11512,10 @@ def ProcessGAMCommand(args):
doShowServiceAccountKeys() doShowServiceAccountKeys()
elif argument in ['browsertoken', 'browsertokens']: elif argument in ['browsertoken', 'browsertokens']:
gapi_cbcm.printshowtokens(False) gapi_cbcm.printshowtokens(False)
elif argument == 'chromeschema':
gapi_chromepolicy.printshow_schemas()
elif argument == 'chromepolicy':
gapi_chromepolicy.printshow_policies()
else: else:
controlflow.invalid_argument_exit(argument, 'gam show') controlflow.invalid_argument_exit(argument, 'gam show')
sys.exit(0) sys.exit(0)

View File

@@ -31,17 +31,17 @@ def build():
return gam.buildGAPIObject('chromepolicy') return gam.buildGAPIObject('chromepolicy')
def print_policies(): def printshow_policies():
svc = build() svc = build()
customer = _get_customerid() customer = _get_customerid()
orgunit = '/' orgunit = None
printer_id = None printer_id = None
app_id = None app_id = None
i = 3 i = 3
while i < len(sys.argv): while i < len(sys.argv):
myarg = sys.argv[i].lower().replace('_', '') myarg = sys.argv[i].lower().replace('_', '')
if myarg in ['orgunit', 'ou']: if myarg in ['ou', 'org', 'orgunit']:
orgunit = sys.argv[i+1] orgunit = _get_orgunit(sys.argv[i+1])
i += 2 i += 2
elif myarg == 'printerid': elif myarg == 'printerid':
printer_id = sys.argv[i+1] printer_id = sys.argv[i+1]
@@ -52,7 +52,8 @@ def print_policies():
else: else:
msg = f'{myarg} is not a valid argument to "gam print chromepolicy"' msg = f'{myarg} is not a valid argument to "gam print chromepolicy"'
controlflow.system_error_exit(3, msg) controlflow.system_error_exit(3, msg)
orgunit = _get_orgunit(orgunit) if not orgunit:
controlflow.system_error_exit(3, 'You must specify an orgunit')
body = { body = {
'policyTargetKey': { 'policyTargetKey': {
'targetResource': orgunit, 'targetResource': orgunit,
@@ -95,12 +96,13 @@ def print_policies():
print(f' {setting}: {value}') print(f' {setting}: {value}')
print() print()
def build_schemas(svc=None):
def build_schemas(svc=None, sfilter=None):
if not svc: if not svc:
svc = build() svc = build()
parent = _get_customerid() parent = _get_customerid()
schemas = gapi.get_all_pages(svc.customers().policySchemas(), 'list', schemas = gapi.get_all_pages(svc.customers().policySchemas(), 'list',
items='policySchemas', parent=parent) items='policySchemas', parent=parent, filter=sfilter)
schema_objects = {} schema_objects = {}
for schema in schemas: for schema in schemas:
schema_name = schema.get('name', '').split('/')[-1] schema_name = schema.get('name', '').split('/')[-1]
@@ -153,11 +155,22 @@ def build_schemas(svc=None):
schema_objects[schema_name.lower()] = schema_dict schema_objects[schema_name.lower()] = schema_dict
return schema_objects return schema_objects
def print_schemas():
def printshow_schemas():
svc = build() svc = build()
schemas = build_schemas(svc) sfilter = None
i = 3
while i < len(sys.argv):
myarg = sys.argv[i].lower().replace('_', '')
if myarg == 'filter':
sfilter = sys.argv[i+1]
i += 2
else:
msg = f'{myarg} is not a valid argument to "gam print chromeschema"'
controlflow.system_error_exit(3, msg)
schemas = build_schemas(svc, sfilter)
for value in schemas.values(): for value in schemas.values():
print(f'{value.get("name")} - {value.get("description")}') print(f'{value.get("name")}: {value.get("description")}')
for val in value['settings'].values(): for val in value['settings'].values():
vtype = val.get('type') vtype = val.get('type')
print(f' {val.get("name")}: {vtype}') print(f' {val.get("name")}: {vtype}')
@@ -165,14 +178,14 @@ def print_schemas():
enums = val.get('enums', []) enums = val.get('enums', [])
descriptions = val.get('descriptions', []) descriptions = val.get('descriptions', [])
for i in range(len(val.get('enums', []))): for i in range(len(val.get('enums', []))):
print(f' {enums[i]} - {descriptions[i]}') print(f' {enums[i]}: {descriptions[i]}')
elif vtype == 'TYPE_BOOL': elif vtype == 'TYPE_BOOL':
pvs = val.get('descriptions') pvs = val.get('descriptions')
for pvi in pvs: for pvi in pvs:
if isinstance(pvi, dict): if isinstance(pvi, dict):
pvalue = pvi.get('value') pvalue = pvi.get('value')
pdescription = pvi.get('description') pdescription = pvi.get('description')
print(f' {pvalue} - {pdescription}') print(f' {pvalue}: {pdescription}')
elif isinstance(pvi, list): elif isinstance(pvi, list):
print(f' {pvi[0]}') print(f' {pvi[0]}')
else: else:
@@ -186,15 +199,15 @@ def delete_policy():
svc = build() svc = build()
customer = _get_customerid() customer = _get_customerid()
schemas = build_schemas(svc) schemas = build_schemas(svc)
orgunit = '/' orgunit = None
printer_id = None printer_id = None
app_id = None app_id = None
i = 3 i = 3
body = {'requests': []} body = {'requests': []}
while i < len(sys.argv): while i < len(sys.argv):
myarg = sys.argv[i].lower().replace('_', '') myarg = sys.argv[i].lower().replace('_', '')
if myarg in ['orgunit', 'ou']: if myarg in ['ou', 'org', 'orgunit']:
orgunit = sys.argv[i+1] orgunit = _get_orgunit(sys.argv[i+1])
i += 2 i += 2
elif myarg == 'printerid': elif myarg == 'printerid':
printer_id = sys.argv[i+1] printer_id = sys.argv[i+1]
@@ -208,7 +221,8 @@ def delete_policy():
else: else:
msg = f'{myarg} is not a valid argument to "gam delete chromepolicy"' msg = f'{myarg} is not a valid argument to "gam delete chromepolicy"'
controlflow.system_error_exit(3, msg) controlflow.system_error_exit(3, msg)
orgunit = _get_orgunit(orgunit) if not orgunit:
controlflow.system_error_exit(3, 'You must specify an orgunit')
for request in body['requests']: for request in body['requests']:
request['policyTargetKey'] = {'targetResource': orgunit} request['policyTargetKey'] = {'targetResource': orgunit}
if printer_id: if printer_id:
@@ -222,14 +236,14 @@ def update_policy():
svc = build() svc = build()
customer = _get_customerid() customer = _get_customerid()
schemas = build_schemas(svc) schemas = build_schemas(svc)
i = 3
body = {'requests': []}
orgunit = None orgunit = None
printer_id = None printer_id = None
app_id = None app_id = None
i = 3
body = {'requests': []}
while i < len(sys.argv): while i < len(sys.argv):
myarg = sys.argv[i].lower().replace('_', '') myarg = sys.argv[i].lower().replace('_', '')
if myarg in ['orgunit', 'ou']: if myarg in ['ou', 'org', 'orgunit']:
orgunit = _get_orgunit(sys.argv[i+1]) orgunit = _get_orgunit(sys.argv[i+1])
i += 2 i += 2
elif myarg == 'printerid': elif myarg == 'printerid':
@@ -245,7 +259,7 @@ def update_policy():
i += 1 i += 1
while i < len(sys.argv): while i < len(sys.argv):
field = sys.argv[i].lower() field = sys.argv[i].lower()
if field in ['orgunit', 'ou', 'printerid', 'appid'] or '.' in field: if field in ['ou', 'org', 'orgunit', 'printerid', 'appid'] or '.' in field:
break # field is actually a new policy, orgunit or app/printer id break # field is actually a new policy, orgunit or app/printer id
expected_fields = ', '.join(schemas[myarg]['settings']) expected_fields = ', '.join(schemas[myarg]['settings'])
if field not in expected_fields: if field not in expected_fields:
@@ -284,10 +298,8 @@ def update_policy():
for request in body['requests']: for request in body['requests']:
request['policyTargetKey'] = {'targetResource': orgunit} request['policyTargetKey'] = {'targetResource': orgunit}
if printer_id: if printer_id:
for request in body['requests']:
request['policyTargetKey']['additionalTargetKeys'] = {'printer_id': printer_id} request['policyTargetKey']['additionalTargetKeys'] = {'printer_id': printer_id}
elif app_id: elif app_id:
for request in body['requests']:
request['policyTargetKey']['additionalTargetKeys'] = {'app_id': app_id} request['policyTargetKey']['additionalTargetKeys'] = {'app_id': app_id}
gapi.call(svc.customers().policies().orgunits(), gapi.call(svc.customers().policies().orgunits(),
'batchModify', 'batchModify',

View File

@@ -82,6 +82,19 @@ def delete():
for printer_id in result.get('failedPrinters', []): for printer_id in result.get('failedPrinters', []):
print(f'ERROR: failed to delete {printer_id.get("printerIds")}') print(f'ERROR: failed to delete {printer_id.get("printerIds")}')
def info():
'''gam info printer'''
cdapi = gapi_directory.build()
customer = _get_customerid()
printer_id = sys.argv[3]
name = f'{customer}/chrome/printers/{printer_id}'
result = gapi.call(cdapi.customers().chrome().printers(),
'get',
name=name)
display.print_json(result)
def print_(): def print_():
'''gam print printers''' '''gam print printers'''
cdapi = gapi_directory.build() cdapi = gapi_directory.build()