def print_models(): '''gam print printermodels''' cdapi = gapi_directory.build() parent = _get_customerid() filter_ = None todrive = False titles = [] rows = [] i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'filter': filter_ = sys.argv[i+1] i += 2 elif myarg == 'todrive': todrive = True i += 1 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam print printermodels') models = gapi.get_all_pages(cdapi.customers().chrome().printers(), 'listPrinterModels', items='printerModels', parent=parent, pageSize=10000, filter=filter_) for model in models: row = {} for key, val in model.items(): if key not in titles: titles.append(key) row[key] = val rows.append(row) display.write_csv_file(rows, titles, 'Printer Models', todrive)
def doUpdateCustomer(): cd = gapi_directory.build() body = {} customer_id = _get_customerid() i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg in ADDRESS_FIELDS_ARGUMENT_MAP: body.setdefault('postalAddress', {}) arg = ADDRESS_FIELDS_ARGUMENT_MAP[myarg] body['postalAddress'][arg] = sys.argv[i + 1] i += 2 elif myarg in ['adminsecondaryemail', 'alternateemail']: body['alternateEmail'] = sys.argv[i + 1] i += 2 elif myarg in ['phone', 'phonenumber']: body['phoneNumber'] = sys.argv[i + 1] i += 2 elif myarg == 'language': body['language'] = sys.argv[i + 1] i += 2 else: controlflow.invalid_argument_exit(myarg, 'gam update customer') if not body: controlflow.system_error_exit( 2, 'no arguments specified for "gam ' 'update customer"') gapi.call(cd.customers(), 'patch', customerKey=customer_id, body=body) print('Updated customer')
def print_(): '''gam print printers''' cdapi = gapi_directory.build() parent = _get_customerid() filter_ = None todrive = False titles = [] rows = [] i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'filter': filter_ = sys.argv[i+1] i += 2 elif myarg == 'todrive': todrive = True i += 1 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam print printermodels') printers = gapi.get_all_pages(cdapi.customers().chrome().printers(), 'list', items='printers', parent=parent, filter=filter_) for printer in printers: if 'orgUnitId' in printer: printer['orgUnitPath'] = gapi_directory_orgunits.orgunit_from_orgunitid( printer['orgUnitId'], cdapi) row = {} for key, val in printer.items(): if key not in titles: titles.append(key) row[key] = val rows.append(row) display.write_csv_file(rows, titles, 'Printers', todrive)
def print_(): cd = gapi_directory.build() todrive = False titles = [ 'domainAliasName', ] csvRows = [] i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'todrive': todrive = True i += 1 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam print domainaliases') results = gapi.call(cd.domainAliases(), 'list', customer=GC_Values[GC_CUSTOMER_ID]) for domainAlias in results['domainAliases']: domainAlias_attributes = {} for attr in domainAlias: if attr in ['kind', 'etag']: continue if attr == 'creationTime': domainAlias[attr] = utils.formatTimestampYMDHMSF( domainAlias[attr]) if attr not in titles: titles.append(attr) domainAlias_attributes[attr] = domainAlias[attr] csvRows.append(domainAlias_attributes) display.write_csv_file(csvRows, titles, 'Domains', todrive)
def print_(): cd = gapi_directory.build() todrive = False titles = [ 'roleId', 'roleName', 'roleDescription', 'isSuperAdminRole', 'isSystemRole' ] fields = f'nextPageToken,items({",".join(titles)})' csvRows = [] i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'todrive': todrive = True i += 1 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam print adminroles') roles = gapi.get_all_pages(cd.roles(), 'list', 'items', customer=GC_Values[GC_CUSTOMER_ID], fields=fields) for role in roles: role_attrib = {} for key, value in list(role.items()): role_attrib[key] = value csvRows.append(role_attrib) display.write_csv_file(csvRows, titles, 'Admin Roles', todrive)
def getOrgUnitId(orgUnit, cd=None): if cd is None: cd = gapi_directory.build() orgUnit = getOrgUnitItem(orgUnit) if orgUnit[:3] == 'id:': return (orgUnit, orgUnit) if orgUnit == '/': result = gapi.call(cd.orgunits(), 'list', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath='/', type='children', fields='organizationUnits(parentOrgUnitId)') if result.get('organizationUnits', []): return (orgUnit, result['organizationUnits'][0]['parentOrgUnitId']) topLevelOrgId = getTopLevelOrgId(cd, '/') if topLevelOrgId: return (orgUnit, topLevelOrgId) return (orgUnit, '/') #Bogus but should never happen result = gapi.call(cd.orgunits(), 'get', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath=encodeOrgUnitPath( makeOrgUnitPathRelative(orgUnit)), fields='orgUnitId') return (orgUnit, result['orgUnitId'])
def print_(): cd = gapi_directory.build() privs = gapi.call(cd.privileges(), 'list', customer=GC_Values[GC_CUSTOMER_ID]) privs = flatten_privilege_list(privs.get('items', [])) display.print_json(privs)
def wait_for_mailbox(users): '''Wait until users mailbox is provisioned.''' cd = gapi_directory.build() i = 0 count = len(users) for user in users: i += 1 user = gam.normalizeEmailAddressOrUID(user) while True: try: result = gapi.call( cd.users(), 'get', 'fields=isMailboxSetup', userKey=user, throw_reasons=[gapi_errors.ErrorReason.USER_NOT_FOUND]) except gapi_errors.GapiUserNotFoundError: print( f'{user} mailboxIsSetup: False (user does not exist yet)') sleep(3) continue mailbox_is_setup = result.get('isMailboxSetup') print(f'{user} mailboxIsSetup: {mailbox_is_setup}') if mailbox_is_setup: break sleep(3)
def delete(): cd = gapi_directory.build() resourceId = sys.argv[3] gapi.call(cd.mobiledevices(), 'delete', resourceId=resourceId, customerId=GC_Values[GC_CUSTOMER_ID])
def update(): cd = gapi_directory.build() body = {} roleId = gam.getRoleId(sys.argv[3]) i = 4 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'privileges': getPrivileges(body, sys.argv[i + 1].upper(), 'update') i += 2 elif myarg == 'description': body['roleDescription'] = sys.argv[i + 1] i += 2 elif myarg == 'name': body['roleName'] = sys.argv[i + 1] i += 2 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam update adminrole') print(f'Updating role {roleId}') gapi.call(cd.roles(), 'patch', customer=GC_Values[GC_CUSTOMER_ID], roleId=roleId, body=body)
def issue_command(): cd = gapi_directory.build() i, devices = getCrOSDeviceEntity(3, cd) body = {} valid_commands = gapi.get_enum_values_minus_unspecified( cd._rootDesc['schemas']['DirectoryChromeosdevicesIssueCommandRequest'] ['properties']['commandType']['enum']) command_map = {} for valid_command in valid_commands: v = valid_command.lower().replace('_', '') command_map[v] = valid_command times_to_check_status = 1 doit = False while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg == 'command': command = sys.argv[i + 1].lower().replace('_', '') if command not in command_map: controlflow.system_error_exit(2, f'expected command of ' \ f'{", ".join(valid_commands)} got {command}') body['commandType'] = command_map[command] i += 2 if command == 'setvolume': body['payload'] = json.dumps({'volume': sys.argv[i]}) i += 1 elif myarg == 'timestocheckstatus': times_to_check_status = int(sys.argv[i + 1]) i += 2 elif myarg == 'doit': doit = True i += 1 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam issuecommand cros') if body['commandType'] == 'WIPE_USERS' and not doit: controlflow.system_error_exit(2, 'wipe_users command requires admin ' \ 'acknowledge user data will be destroyed with the ' \ 'doit argument') if body['commandType'] == 'REMOTE_POWERWASH' and not doit: controlflow.system_error_exit(2, 'remote_powerwash command requires ' \ 'admin acknowledge user data will be destroyed, device will need' \ ' to be reconnected to WiFi and re-enrolled with the doit argument') for device_id in devices: try: result = gapi.call( cd.customer().devices().chromeos(), 'issueCommand', customerId=GC_Values[GC_CUSTOMER_ID], deviceId=device_id, throw_reasons=[gapi_errors.ErrorReason.FOUR_O_O], body=body) except googleapiclient.errors.HttpError: controlflow.system_error_exit(4, '400 response from Google. This ' \ 'usually indicates the devices was not in a state where it will' \ ' accept the command. For example, reboot, set_volume and take_a_screenshot' \ ' require the device to be in auto-start kiosk app mode.') command_id = result.get('commandId') _display_cros_command_result(cd, device_id, command_id, times_to_check_status)
def delete(): cd = gapi_directory.build() roleId = gam.getRoleId(sys.argv[3]) print(f'Deleting role {roleId}') gapi.call(cd.roles(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], roleId=roleId)
def delete(): cd = gapi_directory.build() roleAssignmentId = sys.argv[3] print(f'Deleting Admin Role Assignment {roleAssignmentId}') gapi.call(cd.roleAssignments(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], roleAssignmentId=roleAssignmentId)
def delete(): cd = gapi_directory.build() name = getOrgUnitItem(sys.argv[3]) print(f'Deleting organization {name}') gapi.call(cd.orgunits(), 'delete', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath=encodeOrgUnitPath(makeOrgUnitPathRelative(name)))
def deleteFeature(): cd = gapi_directory.build() featureKey = sys.argv[3] print(f'Deleting feature {featureKey}...') gapi.call(cd.resources().features(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], featureKey=featureKey)
def delete(): cd = gapi_directory.build() domainName = sys.argv[3] print(f'Deleting domain {domainName}') gapi.call(cd.domains(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], domainName=domainName)
def deleteResourceCalendar(): resId = sys.argv[3] cd = gapi_directory.build() print(f'Deleting resource calendar {resId}') gapi.call(cd.resources().calendars(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], calendarResourceId=resId)
def createFeature(): cd = gapi_directory.build() body = _getFeatureAttributes(sys.argv[3:]) print(f'Creating feature {body["name"]}...') gapi.call(cd.resources().features(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body)
def deleteBuilding(): cd = gapi_directory.build() buildingId = getBuildingByNameOrId(cd, sys.argv[3]) print(f'Deleting building {buildingId}...') gapi.call(cd.resources().buildings(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], buildingId=buildingId)
def create(): cd = gapi_directory.build() domain_name = sys.argv[3] body = {'domainName': domain_name} gapi.call(cd.domains(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body) print(f'Added domain {domain_name}')
def createResourceCalendar(): cd = gapi_directory.build() body = {'resourceId': sys.argv[3], 'resourceName': sys.argv[4]} body = _getResourceCalendarAttributes(cd, sys.argv[5:], body) print(f'Creating resource {body["resourceId"]}...') gapi.call(cd.resources().calendars(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body)
def create(): cd = gapi_directory.build() body = {'domainAliasName': sys.argv[3], 'parentDomainName': sys.argv[4]} print(f'Adding {body["domainAliasName"]} alias for ' \ f'{body["parentDomainName"]}') gapi.call(cd.domainAliases(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body)
def signout(users): cd = gapi_directory.build() i = 0 count = len(users) for user in users: i += 1 user = gam.normalizeEmailAddressOrUID(user) print(f'Signing Out {user}{gam.currentCount(i, count)}') gapi.call(cd.users(), 'signOut', soft_errors=True, userKey=user)
def create(): '''gam create printer''' cdapi = gapi_directory.build() parent = _get_customerid() body = _get_printer_attributes(3, cdapi) result = gapi.call(cdapi.customers().chrome().printers(), 'create', parent=parent, body=body) display.print_json(result)
def updateBuilding(): cd = gapi_directory.build() buildingId = getBuildingByNameOrId(cd, sys.argv[3]) body = _getBuildingAttributes(sys.argv[4:]) print(f'Updating building {buildingId}...') gapi.call(cd.resources().buildings(), 'patch', customer=GC_Values[GC_CUSTOMER_ID], buildingId=buildingId, body=body)
def setTrueCustomerId(cd=None): customer_id = GC_Values[GC_CUSTOMER_ID] if customer_id == MY_CUSTOMER: if not cd: cd = gapi_directory.build() result = gapi.call(cd.customers(), 'get', customerKey=customer_id, fields='id') GC_Values[GC_CUSTOMER_ID] = result.get('id', customer_id)
def buildOrgUnitIdToNameMap(): cd = gapi_directory.build() result = gapi.call(cd.orgunits(), 'list', customerId=GC_Values[GC_CUSTOMER_ID], fields='organizationUnits(orgUnitPath,orgUnitId)', type='all') GM_Globals[GM_MAP_ORGUNIT_ID_TO_NAME] = {} for orgUnit in result['organizationUnits']: GM_Globals[GM_MAP_ORGUNIT_ID_TO_NAME][ orgUnit['orgUnitId']] = orgUnit['orgUnitPath']
def printBuildings(): to_drive = False cd = gapi_directory.build() titles = [] csvRows = [] fieldsList = ['buildingId'] # buildings.list() currently doesn't support paging # but should soon, attempt to use it now so we # won't break when it's turned on. fields = 'nextPageToken,buildings(%s)' possible_fields = {} for pfield in cd._rootDesc['schemas']['Building']['properties']: possible_fields[pfield.lower()] = pfield i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'todrive': to_drive = True i += 1 elif myarg == 'allfields': fields = None i += 1 elif myarg in possible_fields: fieldsList.append(possible_fields[myarg]) i += 1 # Allows shorter arguments like "name" instead of "buildingname" elif 'building' + myarg in possible_fields: fieldsList.append(possible_fields['building' + myarg]) i += 1 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam print buildings') if fields: fields = fields % ','.join(fieldsList) buildings = gapi.get_all_pages(cd.resources().buildings(), 'list', 'buildings', customer=GC_Values[GC_CUSTOMER_ID], fields=fields) for building in buildings: building.pop('etags', None) building.pop('etag', None) building.pop('kind', None) if 'buildingId' in building: building['buildingId'] = f'id:{building["buildingId"]}' if 'floorNames' in building: building['floorNames'] = ','.join(building['floorNames']) building = utils.flatten_json(building) for item in building: if item not in titles: titles.append(item) csvRows.append(building) display.sort_csv_titles('buildingId', titles) display.write_csv_file(csvRows, titles, 'Buildings', to_drive)
def info(): cd = gapi_directory.build() alias = sys.argv[3] result = gapi.call(cd.domainAliases(), 'get', customer=GC_Values[GC_CUSTOMER_ID], domainAliasName=alias) if 'creationTime' in result: result['creationTime'] = utils.formatTimestampYMDHMSF( result['creationTime']) display.print_json(result)
def buildRoleIdToNameToIdMap(cd=None): if not cd: cd = gapi_directory.build() result = gapi.get_all_pages(cd.roles(), 'list', 'items', customer=GC_Values[GC_CUSTOMER_ID], fields='nextPageToken,items(roleId,roleName)') GM_Globals[GM_MAP_ROLE_ID_TO_NAME] = {} GM_Globals[GM_MAP_ROLE_NAME_TO_ID] = {} for role in result: GM_Globals[GM_MAP_ROLE_ID_TO_NAME][role['roleId']] = role['roleName'] GM_Globals[GM_MAP_ROLE_NAME_TO_ID][role['roleName']] = role['roleId']