Exemplo n.º 1
0
def printApps():
    cm = build()
    customer = _get_customerid()
    todrive = False
    titles = CHROME_APPS_TITLES
    csvRows = []
    orgunit = None
    pfilter = None
    orderBy = None
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['ou', 'org', 'orgunit']:
            orgunit = _get_orgunit(sys.argv[i + 1])
            i += 2
        elif myarg == 'filter':
            pfilter = sys.argv[i + 1]
            i += 2
        elif myarg == 'orderby':
            orderBy = sys.argv[i + 1].lower().replace('_', '')
            if orderBy not in CHROME_APPS_ORDERBY_CHOICE_MAP:
                controlflow.expected_argument_exit(
                    'orderby', ', '.join(CHROME_APPS_ORDERBY_CHOICE_MAP),
                    orderBy)
            orderBy = CHROME_APPS_ORDERBY_CHOICE_MAP[orderBy]
            i += 2
        else:
            msg = f'{myarg} is not a valid argument to "gam print chromeapps"'
            controlflow.system_error_exit(3, msg)
    if orgunit:
        orgUnitPath = gapi_directory_orgunits.orgunit_from_orgunitid(
            orgunit, None)
        titles.append('orgUnitPath')
    else:
        orgUnitPath = '/'
    gam.printGettingAllItems('Chrome Installed Applications', pfilter)
    page_message = gapi.got_total_items_msg('Chrome Installed Applications',
                                            '...\n')
    apps = gapi.get_all_pages(cm.customers().reports(),
                              'countInstalledApps',
                              'installedApps',
                              page_message=page_message,
                              customer=customer,
                              orgUnitId=orgunit,
                              filter=pfilter,
                              orderBy=orderBy)
    for app in apps:
        if orgunit:
            app['orgUnitPath'] = orgUnitPath
        if 'permissions' in app:
            app['permissions'] = ' '.join(app['permissions'])
        csvRows.append(app)
    display.write_csv_file(csvRows, titles, 'Chrome Installed Applications',
                           todrive)
Exemplo n.º 2
0
def printMatters():
    v = buildGAPIObject()
    todrive = False
    csvRows = []
    initialTitles = ['matterId', 'name', 'description', 'state']
    titles = initialTitles[:]
    view = 'FULL'
    state = None
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in PROJECTION_CHOICES_MAP:
            view = PROJECTION_CHOICES_MAP[myarg]
            i += 1
        elif myarg == 'matterstate':
            valid_states = gapi.get_enum_values_minus_unspecified(
                v._rootDesc['schemas']['Matter']['properties']['state']
                ['enum'])
            state = sys.argv[i + 1].upper()
            if state not in valid_states:
                controlflow.expected_argument_exit('state',
                                                   ', '.join(valid_states),
                                                   state)
            i += 2
        else:
            controlflow.invalid_argument_exit(myarg, 'gam print matters')
    gam.printGettingAllItems('Vault Matters', None)
    page_message = gapi.got_total_items_msg('Vault Matters', '...\n')
    matters = gapi.get_all_pages(v.matters(),
                                 'list',
                                 'matters',
                                 page_message=page_message,
                                 view=view,
                                 state=state)
    for matter in matters:
        display.add_row_titles_to_csv_file(utils.flatten_json(matter), csvRows,
                                           titles)
    display.sort_csv_titles(initialTitles, titles)
    display.write_csv_file(csvRows, titles, 'Vault Matters', todrive)
Exemplo n.º 3
0
def _get_groups_list(ci=None, member=None, parent=None):
    if not ci:
        ci = gapi_cloudidentity.build()
    if not parent:
        gapi_directory_customer.setTrueCustomerId()
        parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    gam.printGettingAllItems('Groups', member)
    page_message = gapi.got_total_items_first_last_msg('Groups')
    if member:
        fields = 'nextPageToken,memberships(groupKey(id),relationType)'
        try:
            groups_to_get = gapi.get_all_pages(
                ci.groups().memberships(),
                'searchTransitiveGroups',
                'memberships',
                throw_reasons=[gapi_errors.ErrorReason.FOUR_O_O],
                message_attribute=['groupKey', 'id'],
                page_message=page_message,
                parent='groups/-',
                query=member,
                pageSize=1000,
                fields=fields)
        except googleapiclient.errors.HttpError:
            controlflow.system_error_exit(
                2, 'enterprisemember requires Enterprise license')
        return [
            group['groupKey']['id'] for group in groups_to_get
            if group['relationType'] == 'DIRECT'
        ]
    else:
        groups_to_get = gapi.get_all_pages(
            ci.groups(),
            'list',
            'groups',
            message_attribute=['groupKey', 'id'],
            page_message=page_message,
            parent=parent,
            view='BASIC',
            pageSize=1000,
            fields='nextPageToken,groups(groupKey(id))')
        return [group['groupKey']['id'] for group in groups_to_get]
Exemplo n.º 4
0
def print_members():
    ci = gapi_cloudidentity.build('cloudidentity_beta')
    todrive = False
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    usemember = None
    roles = []
    titles = ['group']
    csvRows = []
    groups_to_get = []
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['role', 'roles']:
            for role in sys.argv[i + 1].lower().replace(',', ' ').split():
                if role in GROUP_ROLES_MAP:
                    roles.append(GROUP_ROLES_MAP[role])
                else:
                    controlflow.system_error_exit(
                        2,
                        f'{role} is not a valid role for "gam print group-members {myarg}"'
                    )
            i += 2
        elif myarg == 'enterprisemember':
            member = gam.convertUIDtoEmailAddress(
                sys.argv[i + 1], email_types=['user', 'group'])
            usemember = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
            i += 2
        elif myarg in ['cigroup', 'cigroups']:
            group_email = gam.normalizeEmailAddressOrUID(sys.argv[i + 1])
            groups_to_get = [group_email]
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print cigroup-members')
    if not groups_to_get:
        gam.printGettingAllItems('Groups', usemember)
        page_message = gapi.got_total_items_first_last_msg('Groups')
        if usemember:
            try:
                groups_to_get = gapi.get_all_pages(
                    ci.groups().memberships(),
                    'searchTransitiveGroups',
                    'memberships',
                    throw_reasons=[gapi_errors.ErrorReason.FOUR_O_O],
                    message_attribute=['groupKey', 'id'],
                    page_message=page_message,
                    parent='groups/-',
                    query=usemember,
                    pageSize=1000,
                    fields=
                    'nextPageToken,memberships(groupKey(id),relationType)')
            except googleapiclient.errors.HttpError:
                controlflow.system_error_exit(
                    2, f'enterprisemember requires Enterprise license')
            groups_to_get = [
                group['groupKey']['id'] for group in groups_to_get
                if group['relationType'] == 'DIRECT'
            ]
        else:
            groups_to_get = gapi.get_all_pages(
                ci.groups(),
                'list',
                'groups',
                message_attribute=['groupKey', 'id'],
                page_message=page_message,
                parent=parent,
                view='BASIC',
                pageSize=1000,
                fields='nextPageToken,groups(groupKey(id))')
            groups_to_get = [
                group['groupKey']['id'] for group in groups_to_get
            ]
    i = 0
    count = len(groups_to_get)
    for group_email in groups_to_get:
        i += 1

        sys.stderr.write(
            f'Getting members for {group_email}{gam.currentCountNL(i, count)}')
        group_id = group_email_to_id(ci, group_email)
        print(f'Getting members of cigroup {group_email}...')
        page_message = f' {gapi.got_total_items_first_last_msg("Members")}'
        group_members = gapi.get_all_pages(
            ci.groups().memberships(),
            'list',
            'memberships',
            soft_errors=True,
            parent=group_id,
            view='FULL',
            pageSize=500,
            page_message=page_message,
            message_attribute=['memberKey', 'id'])
        #fields='nextPageToken,memberships(memberKey,roles,createTime,updateTime)')
        if roles:
            group_members = filter_members_to_roles(group_members, roles)
        for member in group_members:
            # reduce role to a single value
            member['role'] = get_single_role(member.pop('roles'))
            member = utils.flatten_json(member)
            for title in member:
                if title not in titles:
                    titles.append(title)
            member['group'] = group_email
            csvRows.append(member)
    display.write_csv_file(csvRows, titles, 'Group Members', todrive)
Exemplo n.º 5
0
def print_():
    ci = gapi_cloudidentity.build('cloudidentity_beta')
    i = 3
    members = membersCountOnly = managers = managersCountOnly = owners = ownersCountOnly = False
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    usemember = None
    memberDelimiter = '\n'
    todrive = False
    titles = []
    csvRows = []
    roles = []
    sortHeaders = False
    while i < len(sys.argv):
        myarg = sys.argv[i].lower()
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'enterprisemember':
            member = gam.convertUIDtoEmailAddress(
                sys.argv[i + 1], email_types=['user', 'group'])
            usemember = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
            i += 2
        elif myarg == 'delimiter':
            memberDelimiter = sys.argv[i + 1]
            i += 2
        elif myarg == 'sortheaders':
            sortHeaders = True
            i += 1
        elif myarg in ['members', 'memberscount']:
            roles.append(ROLE_MEMBER)
            members = True
            if myarg == 'memberscount':
                membersCountOnly = True
            i += 1
        elif myarg in ['owners', 'ownerscount']:
            roles.append(ROLE_OWNER)
            owners = True
            if myarg == 'ownerscount':
                ownersCountOnly = True
            i += 1
        elif myarg in ['managers', 'managerscount']:
            roles.append(ROLE_MANAGER)
            managers = True
            if myarg == 'managerscount':
                managersCountOnly = True
            i += 1
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print cigroups')
    if roles:
        if members:
            display.add_titles_to_csv_file([
                'MembersCount',
            ], titles)
            if not membersCountOnly:
                display.add_titles_to_csv_file([
                    'Members',
                ], titles)
        if managers:
            display.add_titles_to_csv_file([
                'ManagersCount',
            ], titles)
            if not managersCountOnly:
                display.add_titles_to_csv_file([
                    'Managers',
                ], titles)
        if owners:
            display.add_titles_to_csv_file([
                'OwnersCount',
            ], titles)
            if not ownersCountOnly:
                display.add_titles_to_csv_file([
                    'Owners',
                ], titles)
    gam.printGettingAllItems('Groups', usemember)
    page_message = gapi.got_total_items_first_last_msg('Groups')
    if usemember:
        try:
            result = gapi.get_all_pages(
                ci.groups().memberships(),
                'searchTransitiveGroups',
                'memberships',
                throw_reasons=[gapi_errors.ErrorReason.FOUR_O_O],
                page_message=page_message,
                message_attribute=['groupKey', 'id'],
                parent='groups/-',
                query=usemember,
                fields=
                'nextPageToken,memberships(group,groupKey(id),relationType)',
                pageSize=1000)
        except googleapiclient.errors.HttpError:
            controlflow.system_error_exit(
                2, f'enterprisemember requires Enterprise license')
        entityList = []
        for entity in result:
            if entity['relationType'] == 'DIRECT':
                entityList.append(
                    gapi.call(ci.groups(), 'get', name=entity['group']))
    else:
        entityList = gapi.get_all_pages(ci.groups(),
                                        'list',
                                        'groups',
                                        page_message=page_message,
                                        message_attribute=['groupKey', 'id'],
                                        parent=parent,
                                        view='FULL',
                                        pageSize=500)
    i = 0
    count = len(entityList)
    for groupEntity in entityList:
        i += 1
        groupEmail = groupEntity['groupKey']['id']
        for k, v in iter(groupEntity.pop('labels', {}).items()):
            if v == '':
                groupEntity[f'labels.{k}'] = True
            else:
                groupEntity[f'labels.{k}'] = v
        group = utils.flatten_json(groupEntity)
        for a_key in group:
            if a_key not in titles:
                titles.append(a_key)
        groupKey_id = groupEntity['name']
        if roles:
            sys.stderr.write(
                f' Getting {roles} for {groupEmail}{gam.currentCountNL(i, count)}'
            )
            page_message = gapi.got_total_items_first_last_msg('Members')
            validRoles, _, _ = gam._getRoleVerification(
                '.'.join(roles), 'nextPageToken,members(email,id,role)')
            groupMembers = gapi.get_all_pages(
                ci.groups().memberships(),
                'list',
                'memberships',
                page_message=page_message,
                message_attribute=['memberKey', 'id'],
                soft_errors=True,
                parent=groupKey_id,
                view='BASIC')
            if members:
                membersList = []
                membersCount = 0
            if managers:
                managersList = []
                managersCount = 0
            if owners:
                ownersList = []
                ownersCount = 0
            for member in groupMembers:
                member_email = member['memberKey']['id']
                role = get_single_role(member.get('roles'))
                if not validRoles or role in validRoles:
                    if role == ROLE_MEMBER:
                        if members:
                            membersCount += 1
                            if not membersCountOnly:
                                membersList.append(member_email)
                    elif role == ROLE_MANAGER:
                        if managers:
                            managersCount += 1
                            if not managersCountOnly:
                                managersList.append(member_email)
                    elif role == ROLE_OWNER:
                        if owners:
                            ownersCount += 1
                            if not ownersCountOnly:
                                ownersList.append(member_email)
                    elif members:
                        membersCount += 1
                        if not membersCountOnly:
                            membersList.append(member_email)
            if members:
                group['MembersCount'] = membersCount
                if not membersCountOnly:
                    group['Members'] = memberDelimiter.join(membersList)
            if managers:
                group['ManagersCount'] = managersCount
                if not managersCountOnly:
                    group['Managers'] = memberDelimiter.join(managersList)
            if owners:
                group['OwnersCount'] = ownersCount
                if not ownersCountOnly:
                    group['Owners'] = memberDelimiter.join(ownersList)
        csvRows.append(group)
    if sortHeaders:
        display.sort_csv_titles(['name', 'groupKey.id'], titles)
    display.write_csv_file(csvRows, titles, 'Groups', todrive)
Exemplo n.º 6
0
def print_():
    print_order = [
        'orgUnitPath', 'orgUnitId', 'name', 'description', 'parentOrgUnitPath',
        'parentOrgUnitId', 'blockInheritance'
    ]
    cd = gapi_directory.build()
    listType = 'all'
    orgUnitPath = '/'
    todrive = False
    fields = ['orgUnitPath', 'name', 'orgUnitId', 'parentOrgUnitId']
    titles = []
    csvRows = []
    parentOrgIds = []
    retrievedOrgIds = []
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'toplevelonly':
            listType = 'children'
            i += 1
        elif myarg == 'fromparent':
            orgUnitPath = getOrgUnitItem(sys.argv[i + 1])
            i += 2
        elif myarg == 'allfields':
            fields = None
            i += 1
        elif myarg == 'fields':
            fields += sys.argv[i + 1].split(',')
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i], 'gam print orgs')
    gam.printGettingAllItems('Organizational Units', None)
    if fields:
        get_fields = ','.join(fields)
        list_fields = f'organizationUnits({get_fields})'
    else:
        list_fields = None
        get_fields = None
    orgs = gapi.call(cd.orgunits(),
                     'list',
                     customerId=GC_Values[GC_CUSTOMER_ID],
                     type=listType,
                     orgUnitPath=orgUnitPath,
                     fields=list_fields)
    if not 'organizationUnits' in orgs:
        topLevelOrgId = getTopLevelOrgId(cd, orgUnitPath)
        if topLevelOrgId:
            parentOrgIds.append(topLevelOrgId)
        orgunits = []
    else:
        orgunits = orgs['organizationUnits']
    for row in orgunits:
        retrievedOrgIds.append(row['orgUnitId'])
        if row['parentOrgUnitId'] not in parentOrgIds:
            parentOrgIds.append(row['parentOrgUnitId'])
    missing_parents = set(parentOrgIds) - set(retrievedOrgIds)
    for missing_parent in missing_parents:
        try:
            result = gapi.call(cd.orgunits(),
                               'get',
                               throw_reasons=['required'],
                               customerId=GC_Values[GC_CUSTOMER_ID],
                               orgUnitPath=missing_parent,
                               fields=get_fields)
            orgunits.append(result)
        except:
            pass
    for row in orgunits:
        orgEntity = {}
        for key, value in list(row.items()):
            if key in ['kind', 'etag', 'etags']:
                continue
            if key not in titles:
                titles.append(key)
            orgEntity[key] = value
        csvRows.append(orgEntity)
    for title in titles:
        if title not in print_order:
            print_order.append(title)
    titles = sorted(titles, key=print_order.index)
    # sort results similar to how they list in admin console
    csvRows.sort(key=lambda x: x['orgUnitPath'].lower(), reverse=False)
    display.write_csv_file(csvRows, titles, 'Orgs', todrive)
Exemplo n.º 7
0
def printVersions():
    cm = build()
    customer = _get_customerid()
    todrive = False
    titles = CHROME_VERSIONS_TITLES
    csvRows = []
    orgunit = None
    startDate = None
    endDate = None
    pfilter = None
    reverse = False
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['ou', 'org', 'orgunit']:
            orgunit = _get_orgunit(sys.argv[i + 1])
            i += 2
        elif myarg in CROS_START_ARGUMENTS:
            startDate = _getFilterDate(sys.argv[i +
                                                1]).strftime(YYYYMMDD_FORMAT)
            i += 2
        elif myarg in CROS_END_ARGUMENTS:
            endDate = _getFilterDate(sys.argv[i + 1]).strftime(YYYYMMDD_FORMAT)
            i += 2
        elif myarg == 'recentfirst':
            reverse = True
            i += 1
        else:
            msg = f'{myarg} is not a valid argument to "gam print chromeversions"'
            controlflow.system_error_exit(3, msg)
    if endDate:
        pfilter = f'last_active_date<={endDate}'
    if startDate:
        if pfilter:
            pfilter += ' AND '
        else:
            pfilter = ''
        pfilter += f'last_active_date>={startDate}'
    if orgunit:
        orgUnitPath = gapi_directory_orgunits.orgunit_from_orgunitid(
            orgunit, None)
        titles.append('orgUnitPath')
    else:
        orgUnitPath = '/'
    gam.printGettingAllItems('Chrome Versions', pfilter)
    page_message = gapi.got_total_items_msg('Chrome Versions', '...\n')
    versions = gapi.get_all_pages(cm.customers().reports(),
                                  'countChromeVersions',
                                  'browserVersions',
                                  page_message=page_message,
                                  customer=customer,
                                  orgUnitId=orgunit,
                                  filter=pfilter)
    for version in sorted(versions,
                          key=lambda k: k.get('version', 'Unknown'),
                          reverse=reverse):
        if orgunit:
            version['orgUnitPath'] = orgUnitPath
        if 'version' not in version:
            version['version'] = 'Unknown'
        csvRows.append(version)
    display.write_csv_file(csvRows, titles, 'Chrome Versions', todrive)
Exemplo n.º 8
0
def printShowCrosTelemetry(mode):
    cm = build()
    cd = None
    parent = _get_customerid()
    todrive = False
    filter_ = None
    readMask = []
    orgUnitIdPathMap = {}
    diskpercentonly = False
    showOrgUnitPath = False
    supported_readmask_values = list(
        cm._rootDesc['schemas']['GoogleChromeManagementV1TelemetryDevice']
        ['properties'].keys())
    supported_readmask_values.sort()
    supported_readmask_map = {
        item.lower(): item
        for item in supported_readmask_values
    }
    i = 3
    if mode == 'info':
        if i >= len(sys.argv):
            controlflow.system_error_exit(
                3, f'<SerialNumber> required for "gam info crostelemetry"')
        filter_ = f'serialNumber={sys.argv[i]}'
        i += 1
        mode = 'show'
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'fields':
            field_list = sys.argv[i + 1].lower().split(',')
            for field_item in field_list:
                if field_item not in supported_readmask_map:
                    controlflow.expected_argument_exit(
                        'fields', ', '.join(supported_readmask_values),
                        field_item)
                else:
                    readMask.append(supported_readmask_map[field_item])
            i += 2
        elif myarg in supported_readmask_map:
            readMask.append(supported_readmask_map[myarg])
            i += 1
        elif myarg == 'filter':
            filter_ = sys.argv[i + 1]
            i += 2
        elif myarg in ['ou', 'org', 'orgunit']:
            _, orgUnitId = gapi_directory_orgunits.getOrgUnitId(
                sys.argv[i + 1], None)
            filter_ = f'orgUnitId={orgUnitId[3:]}'
            i += 2
        elif myarg == 'crossn':
            filter_ = f'serialNumber={sys.argv[i + 1]}'
            i += 2
        elif myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'showorgunitpath':
            showOrgUnitPath = True
            cd = gapi_directory.build()
            i += 1
        elif myarg == 'storagepercentonly':
            diskpercentonly = True
            i += 1
        else:
            msg = f'{myarg} is not a valid argument to "gam print crostelemetry"'
            controlflow.system_error_exit(3, msg)
    if not readMask:
        readMask = ','.join(supported_readmask_values)
    else:
        if 'deviceId' not in readMask:
            readMask.append('deviceId')
        readMask = ','.join(readMask)
    gam.printGettingAllItems('Chrome Device Telemetry...', filter_)
    page_message = gapi.got_total_items_msg('Chrome Device Telemetry', '...\n')
    devices = gapi.get_all_pages(cm.customers().telemetry().devices(),
                                 'list',
                                 'devices',
                                 page_message=page_message,
                                 parent=parent,
                                 filter=filter_,
                                 readMask=readMask)
    for device in devices:
        if 'totalDiskBytes' in device.get(
                'storageInfo', {}) and 'availableDiskBytes' in device.get(
                    'storageInfo', {}):
            disk_avail = int(device['storageInfo']['availableDiskBytes'])
            disk_size = int(device['storageInfo']['totalDiskBytes'])
            if diskpercentonly:
                device['storageInfo'] = {}
            device['storageInfo']['percentDiskFree'] = int(
                (disk_avail / disk_size) * 100)
            device['storageInfo']['percentDiskUsed'] = 100 - device[
                'storageInfo']['percentDiskFree']
        for cpuStatusReport in device.get('cpuStatusReport', []):
            for tempInfo in cpuStatusReport.pop('cpuTemperatureInfo', []):
                cpuStatusReport[
                    f"cpuTemperatureInfo.{tempInfo['label'].strip()}"] = tempInfo[
                        'temperatureCelsius']
        if showOrgUnitPath:
            orgUnitId = device.get('orgUnitId')
            if orgUnitId not in orgUnitIdPathMap:
                orgUnitIdPathMap[
                    orgUnitId] = gapi_directory_orgunits.orgunit_from_orgunitid(
                        orgUnitId, cd)
            device['orgUnitPath'] = orgUnitIdPathMap[orgUnitId]
    if mode == 'show':
        for device in devices:
            display.print_json(device)
            print()
            print()
    else:
        csvRows = []
        titles = []
        for device in devices:
            display.add_row_titles_to_csv_file(utils.flatten_json(device),
                                               csvRows, titles)
        display.write_csv_file(csvRows, titles, 'Telemetry Devices', todrive)
Exemplo n.º 9
0
def doPrintCrosDevices():
    def _getSelectedLists(myarg):
        if myarg in CROS_ACTIVE_TIME_RANGES_ARGUMENTS:
            selectedLists['activeTimeRanges'] = True
        elif myarg in CROS_RECENT_USERS_ARGUMENTS:
            selectedLists['recentUsers'] = True
        elif myarg in CROS_DEVICE_FILES_ARGUMENTS:
            selectedLists['deviceFiles'] = True
        elif myarg in CROS_CPU_STATUS_REPORTS_ARGUMENTS:
            selectedLists['cpuStatusReports'] = True
        elif myarg in CROS_DISK_VOLUME_REPORTS_ARGUMENTS:
            selectedLists['diskVolumeReports'] = True
        elif myarg in CROS_SYSTEM_RAM_FREE_REPORTS_ARGUMENTS:
            selectedLists['systemRamFreeReports'] = True

    cd = gapi_directory.build()
    todrive = False
    fieldsList = []
    fieldsTitles = {}
    titles = []
    csvRows = []
    display.add_field_to_csv_file('deviceid', CROS_ARGUMENT_TO_PROPERTY_MAP,
                                  fieldsList, fieldsTitles, titles)
    projection = orderBy = sortOrder = orgUnitPath = None
    queries = [None]
    noLists = sortHeaders = False
    selectedLists = {}
    startDate = endDate = None
    listLimit = 0
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg in ['query', 'queries']:
            queries = gam.getQueries(myarg, sys.argv[i + 1])
            i += 2
        elif myarg == 'limittoou':
            orgUnitPath = gapi_directory_orgunits.getOrgUnitItem(sys.argv[i +
                                                                          1])
            i += 2
        elif myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'nolists':
            noLists = True
            selectedLists = {}
            i += 1
        elif myarg == 'listlimit':
            listLimit = gam.getInteger(sys.argv[i + 1], myarg, minVal=0)
            i += 2
        elif myarg in CROS_START_ARGUMENTS:
            startDate = _getFilterDate(sys.argv[i + 1])
            i += 2
        elif myarg in CROS_END_ARGUMENTS:
            endDate = _getFilterDate(sys.argv[i + 1])
            i += 2
        elif myarg == 'orderby':
            orderBy = sys.argv[i + 1].lower().replace('_', '')
            validOrderBy = [
                'location', 'user', 'lastsync', 'notes', 'serialnumber',
                'status', 'supportenddate'
            ]
            if orderBy not in validOrderBy:
                controlflow.expected_argument_exit('orderby',
                                                   ', '.join(validOrderBy),
                                                   orderBy)
            if orderBy == 'location':
                orderBy = 'annotatedLocation'
            elif orderBy == 'user':
                orderBy = 'annotatedUser'
            elif orderBy == 'lastsync':
                orderBy = 'lastSync'
            elif orderBy == 'serialnumber':
                orderBy = 'serialNumber'
            elif orderBy == 'supportenddate':
                orderBy = 'supportEndDate'
            i += 2
        elif myarg in SORTORDER_CHOICES_MAP:
            sortOrder = SORTORDER_CHOICES_MAP[myarg]
            i += 1
        elif myarg in PROJECTION_CHOICES_MAP:
            projection = PROJECTION_CHOICES_MAP[myarg]
            sortHeaders = True
            if projection == 'FULL':
                fieldsList = []
            else:
                fieldsList = CROS_BASIC_FIELDS_LIST[:]
            i += 1
        elif myarg == 'allfields':
            projection = 'FULL'
            sortHeaders = True
            fieldsList = []
            i += 1
        elif myarg == 'sortheaders':
            sortHeaders = True
            i += 1
        elif myarg in CROS_LISTS_ARGUMENTS:
            _getSelectedLists(myarg)
            i += 1
        elif myarg in CROS_ARGUMENT_TO_PROPERTY_MAP:
            display.add_field_to_fields_list(myarg,
                                             CROS_ARGUMENT_TO_PROPERTY_MAP,
                                             fieldsList)
            i += 1
        elif myarg == 'fields':
            fieldNameList = sys.argv[i + 1]
            for field in fieldNameList.lower().replace(',', ' ').split():
                if field in CROS_LISTS_ARGUMENTS:
                    _getSelectedLists(field)
                elif field in CROS_ARGUMENT_TO_PROPERTY_MAP:
                    display.add_field_to_fields_list(
                        field, CROS_ARGUMENT_TO_PROPERTY_MAP, fieldsList)
                else:
                    controlflow.invalid_argument_exit(field,
                                                      'gam print cros fields')
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i], 'gam print cros')
    if selectedLists:
        noLists = False
        projection = 'FULL'
        for selectList in selectedLists:
            display.add_field_to_fields_list(selectList,
                                             CROS_ARGUMENT_TO_PROPERTY_MAP,
                                             fieldsList)
    if fieldsList:
        fieldsList.append('deviceId')
        fields = f'nextPageToken,chromeosdevices({",".join(set(fieldsList))})'.replace(
            '.', '/')
    else:
        fields = None
    for query in queries:
        gam.printGettingAllItems('CrOS Devices', query)
        page_message = gapi.got_total_items_msg('CrOS Devices', '...\n')
        all_cros = gapi.get_all_pages(cd.chromeosdevices(),
                                      'list',
                                      'chromeosdevices',
                                      page_message=page_message,
                                      query=query,
                                      customerId=GC_Values[GC_CUSTOMER_ID],
                                      projection=projection,
                                      orgUnitPath=orgUnitPath,
                                      orderBy=orderBy,
                                      sortOrder=sortOrder,
                                      fields=fields)
        for cros in all_cros:
            _checkTPMVulnerability(cros)
        if not noLists and not selectedLists:
            for cros in all_cros:
                if 'notes' in cros:
                    cros['notes'] = cros['notes'].replace('\n', '\\n')
                if 'autoUpdateExpiration' in cros:
                    cros['autoUpdateExpiration'] = utils.formatTimestampYMD(
                        cros['autoUpdateExpiration'])
                for cpuStatusReport in cros.get('cpuStatusReports', []):
                    tempInfos = cpuStatusReport.get('cpuTemperatureInfo', [])
                    for tempInfo in tempInfos:
                        tempInfo['label'] = tempInfo['label'].strip()
                display.add_row_titles_to_csv_file(
                    utils.flatten_json(cros, listLimit=listLimit), csvRows,
                    titles)
            continue
        for cros in all_cros:
            if 'notes' in cros:
                cros['notes'] = cros['notes'].replace('\n', '\\n')
            if 'autoUpdateExpiration' in cros:
                cros['autoUpdateExpiration'] = utils.formatTimestampYMD(
                    cros['autoUpdateExpiration'])
            row = {}
            for attrib in cros:
                if attrib not in {
                        'kind', 'etag', 'tpmVersionInfo', 'recentUsers',
                        'activeTimeRanges', 'deviceFiles', 'cpuStatusReports',
                        'diskVolumeReports', 'systemRamFreeReports'
                }:
                    row[attrib] = cros[attrib]
            if selectedLists.get('activeTimeRanges'):
                timergs = cros.get('activeTimeRanges', [])
            else:
                timergs = []
            activeTimeRanges = _filterTimeRanges(timergs, startDate, endDate)
            if selectedLists.get('recentUsers'):
                recentUsers = cros.get('recentUsers', [])
            else:
                recentUsers = []
            if selectedLists.get('deviceFiles'):
                device_files = cros.get('deviceFiles', [])
            else:
                device_files = []
            deviceFiles = _filterCreateReportTime(device_files, 'createTime',
                                                  startDate, endDate)
            if selectedLists.get('cpuStatusReports'):
                cpu_reports = cros.get('cpuStatusReports', [])
            else:
                cpu_reports = []
            cpuStatusReports = _filterCreateReportTime(cpu_reports,
                                                       'reportTime', startDate,
                                                       endDate)
            if selectedLists.get('diskVolumeReports'):
                diskVolumeReports = cros.get('diskVolumeReports', [])
            else:
                diskVolumeReports = []
            if selectedLists.get('systemRamFreeReports'):
                ram_reports = cros.get('systemRamFreeReports', [])
            else:
                ram_reports = []
            systemRamFreeReports = _filterCreateReportTime(
                ram_reports, 'reportTime', startDate, endDate)
            if noLists or (not activeTimeRanges and \
                           not recentUsers and \
                           not deviceFiles and \
                           not cpuStatusReports and \
                           not diskVolumeReports and \
                           not systemRamFreeReports):
                display.add_row_titles_to_csv_file(row, csvRows, titles)
                continue
            lenATR = len(activeTimeRanges)
            lenRU = len(recentUsers)
            lenDF = len(deviceFiles)
            lenCSR = len(cpuStatusReports)
            lenDVR = len(diskVolumeReports)
            lenSRFR = len(systemRamFreeReports)
            max_len = max(lenATR, lenRU, lenDF, lenCSR, lenDVR, lenSRFR)
            for i in range(min(max_len, listLimit or max_len)):
                nrow = row.copy()
                if i < lenATR:
                    nrow['activeTimeRanges.date'] = \
                        activeTimeRanges[i]['date']
                    nrow['activeTimeRanges.activeTime'] = \
                        str(activeTimeRanges[i]['activeTime'])
                    active_time = activeTimeRanges[i]['activeTime']
                    nrow['activeTimeRanges.duration'] = \
                        utils.formatMilliSeconds(active_time)
                    nrow['activeTimeRanges.minutes'] = active_time // 60000
                if i < lenRU:
                    nrow['recentUsers.type'] = recentUsers[i]['type']
                    nrow['recentUsers.email'] = recentUsers[i].get('email')
                    if not nrow['recentUsers.email']:
                        if nrow['recentUsers.type'] == 'USER_TYPE_UNMANAGED':
                            nrow['recentUsers.email'] = 'UnmanagedUser'
                        else:
                            nrow['recentUsers.email'] = 'Unknown'
                if i < lenDF:
                    nrow['deviceFiles.type'] = deviceFiles[i]['type']
                    nrow['deviceFiles.createTime'] = \
                        deviceFiles[i]['createTime']
                if i < lenCSR:
                    nrow['cpuStatusReports.reportTime'] = \
                        cpuStatusReports[i]['reportTime']
                    tempInfos = cpuStatusReports[i].get(
                        'cpuTemperatureInfo', [])
                    for tempInfo in tempInfos:
                        label = tempInfo['label'].strip()
                        base = 'cpuStatusReports.cpuTemperatureInfo.'
                        nrow[f'{base}{label}'] = tempInfo['temperature']
                    cpu_field = 'cpuUtilizationPercentageInfo'
                    if cpu_field in cpuStatusReports[i]:
                        cpu_reports = cpuStatusReports[i][cpu_field]
                        cpu_pcts = [str(x) for x in cpu_reports]
                        nrow[f'cpuStatusReports.{cpu_field}'] = ','.join(
                            cpu_pcts)
                if i < lenDVR:
                    volumeInfo = diskVolumeReports[i]['volumeInfo']
                    j = 0
                    vfield = 'diskVolumeReports.volumeInfo.'
                    for volume in volumeInfo:
                        nrow[f'{vfield}{j}.volumeId'] = \
                            volume['volumeId']
                        nrow[f'{vfield}{j}.storageFree'] = \
                            volume['storageFree']
                        nrow[f'{vfield}{j}.storageTotal'] = \
                            volume['storageTotal']
                        j += 1
                if i < lenSRFR:
                    nrow['systemRamFreeReports.reportTime'] = \
                        systemRamFreeReports[i]['reportTime']
                    ram_reports = systemRamFreeReports[i]['systemRamFreeInfo']
                    ram_info = [str(x) for x in ram_reports]
                    nrow['systenRamFreeReports.systemRamFreeInfo'] = \
                        ','.join(ram_info)
                display.add_row_titles_to_csv_file(nrow, csvRows, titles)
    if sortHeaders:
        display.sort_csv_titles([
            'deviceId',
        ], titles)
    display.write_csv_file(csvRows, titles, 'CrOS', todrive)
Exemplo n.º 10
0
def doPrintCrosActivity():
    cd = gapi_directory.build()
    todrive = False
    titles = [
        'deviceId', 'annotatedAssetId', 'annotatedLocation', 'serialNumber',
        'orgUnitPath'
    ]
    csvRows = []
    fieldsList = [
        'deviceId', 'annotatedAssetId', 'annotatedLocation', 'serialNumber',
        'orgUnitPath'
    ]
    startDate = endDate = None
    selectActiveTimeRanges = selectDeviceFiles = selectRecentUsers = False
    listLimit = 0
    delimiter = ','
    orgUnitPath = None
    queries = [None]
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg in ['query', 'queries']:
            queries = gam.getQueries(myarg, sys.argv[i + 1])
            i += 2
        elif myarg == 'limittoou':
            orgUnitPath = gapi_directory_orgunits.getOrgUnitItem(sys.argv[i +
                                                                          1])
            i += 2
        elif myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in CROS_ACTIVE_TIME_RANGES_ARGUMENTS:
            selectActiveTimeRanges = True
            i += 1
        elif myarg in CROS_DEVICE_FILES_ARGUMENTS:
            selectDeviceFiles = True
            i += 1
        elif myarg in CROS_RECENT_USERS_ARGUMENTS:
            selectRecentUsers = True
            i += 1
        elif myarg == 'both':
            selectActiveTimeRanges = selectRecentUsers = True
            i += 1
        elif myarg == 'all':
            selectActiveTimeRanges = selectDeviceFiles = True
            selectRecentUsers = True
            i += 1
        elif myarg in CROS_START_ARGUMENTS:
            startDate = _getFilterDate(sys.argv[i + 1])
            i += 2
        elif myarg in CROS_END_ARGUMENTS:
            endDate = _getFilterDate(sys.argv[i + 1])
            i += 2
        elif myarg == 'listlimit':
            listLimit = gam.getInteger(sys.argv[i + 1], myarg, minVal=0)
            i += 2
        elif myarg == 'delimiter':
            delimiter = sys.argv[i + 1]
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print crosactivity')
    if not selectActiveTimeRanges and \
       not selectDeviceFiles and \
       not selectRecentUsers:
        selectActiveTimeRanges = selectRecentUsers = True
    if selectRecentUsers:
        fieldsList.append('recentUsers')
        display.add_titles_to_csv_file([
            'recentUsers.email',
        ], titles)
    if selectActiveTimeRanges:
        fieldsList.append('activeTimeRanges')
        titles_to_add = [
            'activeTimeRanges.date', 'activeTimeRanges.duration',
            'activeTimeRanges.minutes'
        ]
        display.add_titles_to_csv_file(titles_to_add, titles)
    if selectDeviceFiles:
        fieldsList.append('deviceFiles')
        titles_to_add = ['deviceFiles.type', 'deviceFiles.createTime']
        display.add_titles_to_csv_file(titles_to_add, titles)
    fields = f'nextPageToken,chromeosdevices({",".join(fieldsList)})'
    for query in queries:
        gam.printGettingAllItems('CrOS Devices', query)
        page_message = gapi.got_total_items_msg('CrOS Devices', '...\n')
        all_cros = gapi.get_all_pages(cd.chromeosdevices(),
                                      'list',
                                      'chromeosdevices',
                                      page_message=page_message,
                                      query=query,
                                      customerId=GC_Values[GC_CUSTOMER_ID],
                                      projection='FULL',
                                      fields=fields,
                                      orgUnitPath=orgUnitPath)
        for cros in all_cros:
            row = {}
            skip_attribs = ['recentUsers', 'activeTimeRanges', 'deviceFiles']
            for attrib in cros:
                if attrib not in skip_attribs:
                    row[attrib] = cros[attrib]
            if selectActiveTimeRanges:
                activeTimeRanges = _filterTimeRanges(
                    cros.get('activeTimeRanges', []), startDate, endDate)
                lenATR = len(activeTimeRanges)
                num_ranges = min(lenATR, listLimit or lenATR)
                for activeTimeRange in activeTimeRanges[:num_ranges]:
                    newrow = row.copy()
                    newrow['activeTimeRanges.date'] = activeTimeRange['date']
                    active_time = activeTimeRange['activeTime']
                    newrow['activeTimeRanges.duration'] = \
                        utils.formatMilliSeconds(active_time)
                    newrow['activeTimeRanges.minutes'] = \
                        activeTimeRange['activeTime']//60000
                    csvRows.append(newrow)
            if selectRecentUsers:
                recentUsers = cros.get('recentUsers', [])
                lenRU = len(recentUsers)
                num_ranges = min(lenRU, listLimit or lenRU)
                recent_users = []
                for recentUser in recentUsers[:num_ranges]:
                    useremail = recentUser.get('email')
                    if not useremail:
                        if recentUser['type'] == 'USER_TYPE_UNMANAGED':
                            useremail = 'UnmanagedUser'
                        else:
                            useremail = 'Unknown'
                    recent_users.append(useremail)
                row['recentUsers.email'] = delimiter.join(recent_users)
                csvRows.append(row)
            if selectDeviceFiles:
                deviceFiles = _filterCreateReportTime(
                    cros.get('deviceFiles', []), 'createTime', startDate,
                    endDate)
                lenDF = len(deviceFiles)
                num_ranges = min(lenDF, listLimit or lenDF)
                for deviceFile in deviceFiles[:num_ranges]:
                    newrow = row.copy()
                    newrow['deviceFiles.type'] = deviceFile['type']
                    create_time = deviceFile['createTime']
                    newrow['deviceFiles.createTime'] = create_time
                    csvRows.append(newrow)
    display.write_csv_file(csvRows, titles, 'CrOS Activity', todrive)
Exemplo n.º 11
0
def printHistory():
    cv = build()
    entityType = sys.argv[3].lower().replace('_', '')
    if entityType not in CHROME_HISTORY_ENTITY_CHOICES:
        msg = f'{entityType} is not a valid argument to "gam print chromehistory"'
        controlflow.system_error_exit(3, msg)
    todrive = False
    csvRows = []
    cplatform = 'all'
    channel = 'all'
    version = 'all'
    kwargs = {}
    orderByList = []
    i = 4
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif entityType != 'platforms' and myarg == 'platform':
            cplatform = sys.argv[i + 1].lower().replace('_', '')
            platform_map = get_platform_map(cv)
            if cplatform not in platform_map:
                controlflow.expected_argument_exit('platform',
                                                   ', '.join(platform_map),
                                                   cplatform)
            cplatform = platform_map[cplatform]
            i += 2
        elif entityType in {'versions', 'releases'} and myarg == 'channel':
            channel = sys.argv[i + 1].lower().replace('_', '')
            channel_map = get_channel_map(cv)
            if channel not in channel_map:
                controlflow.expected_argument_exit('channel',
                                                   ', '.join(channel_map),
                                                   channel)
            channel = channel_map[channel]
            i += 2
        elif entityType == 'releases' and myarg == 'version':
            version = sys.argv[i + 1]
            i += 2
        elif entityType in {'versions', 'releases'} and myarg == 'orderby':
            fieldName = sys.argv[i + 1].lower().replace('_', '')
            i += 2
            if fieldName in CHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP[entityType]:
                fieldName = CHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP[entityType][fieldName]
                orderBy = ''
                if i < len(sys.argv):
                    orderBy = sys.argv[i].lower()
                    if orderBy in SORTORDER_CHOICES_MAP:
                        orderBy = SORTORDER_CHOICES_MAP[orderBy]
                        i += 1
                if orderBy != 'DESCENDING':
                    orderByList.append(fieldName)
                else:
                    orderByList.append(f'{fieldName} desc')
            else:
                controlflow.expected_argument_exit('orderby',
                                                   ', '.join(CHROME_VERSIONHISTORY_ORDERBY_CHOICE_MAP[entityType]),
                                                   fieldName)
        elif entityType in {'versions', 'releases'} and myarg == 'filter':
            kwargs['filter'] = sys.argv[i + 1]
            i += 2
        else:
            msg = f'{myarg} is not a valid argument to "gam print chromehistory {entityType}"'
            controlflow.system_error_exit(3, msg)
    if orderByList:
        kwargs['orderBy'] = ','.join(orderByList)
    if entityType == 'platforms':
        svc = cv.platforms()
        parent = 'chrome'
    elif entityType == 'channels':
        svc = cv.platforms().channels()
        parent = f'chrome/platforms/{cplatform}'
    elif entityType == 'versions':
        svc = cv.platforms().channels().versions()
        parent = f'chrome/platforms/{cplatform}/channels/{channel}'
    else: #elif entityType == 'releases'
        svc = cv.platforms().channels().versions().releases()
        parent = f'chrome/platforms/{cplatform}/channels/{channel}/versions/{version}'
    reportTitle = f'Chrome Version History {entityType.capitalize()}'
    page_message = gapi.got_total_items_msg(reportTitle, '...\n')
    gam.printGettingAllItems(reportTitle, None)
    citems = gapi.get_all_pages(svc, 'list', entityType,
                                page_message=page_message,
                                parent=parent,
                                fields=f'nextPageToken,{entityType}',
                                **kwargs)
    for citem in citems:
        for key in list(citem):
            if key.endswith('Type'):
                newkey = key[:-4]
                citem[newkey] = citem.pop(key)
        if 'channel' in citem:
            citem['channel'] = citem['channel'].lower()
        else:
            channel_match = re.search(r"\/channels\/([^/]*)", citem['name'])
            if channel_match:
                try:
                    citem['channel'] = channel_match.group(1)
                except IndexError:
                    pass
        if 'platform' in citem:
            citem['platform'] = citem['platform'].lower()
        else:
            platform_match = re.search(r"\/platforms\/([^/]*)", citem['name'])
            if platform_match:
                try:
                    citem['platform'] = platform_match.group(1)
                except IndexError:
                    pass

        if citem.get('version', '').count('.') == 3:
            citem['major_version'], \
            citem['minor_version'], \
            citem['build'], \
            citem['patch'] = citem['version'].split('.')
        citem.pop('name')
        csvRows.append(utils.flatten_json(citem))
    display.write_csv_file(csvRows, CHROME_VERSIONHISTORY_TITLES[entityType], reportTitle, todrive)
Exemplo n.º 12
0
def print_():
    '''gam print userinvitations'''
    svc = gapi_cloudidentity.build('cloudidentity_beta')
    customer = _get_customerid()
    todrive = False
    titles = ['name', 'state', 'updateTime']
    rows = []
    filter_ = None
    orderByList = []
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'state':
            state = sys.argv[i + 1].lower().replace('_', '')
            if state in USERINVITATION_STATE_CHOICES_MAP:
                filter_ = f"state=='{USERINVITATION_STATE_CHOICES_MAP[state]}'"
            else:
                controlflow.expected_argument_exit(
                    'state', ', '.join(USERINVITATION_STATE_CHOICES_MAP),
                    state)
            i += 2
        elif myarg == 'orderby':
            fieldName = sys.argv[i + 1].lower()
            i += 2
            if fieldName in USERINVITATION_ORDERBY_CHOICES_MAP:
                fieldName = USERINVITATION_ORDERBY_CHOICES_MAP[fieldName]
                orderBy = ''
                if i < len(sys.argv):
                    orderBy = sys.argv[i].lower()
                    if orderBy in SORTORDER_CHOICES_MAP:
                        orderBy = SORTORDER_CHOICES_MAP[orderBy]
                        i += 1
                if orderBy != 'DESCENDING':
                    orderByList.append(fieldName)
                else:
                    orderByList.append(f'{fieldName} desc')
            else:
                controlflow.expected_argument_exit(
                    'orderby',
                    ', '.join(sorted(USERINVITATION_ORDERBY_CHOICES_MAP)),
                    fieldName)
        elif myarg == 'todrive':
            todrive = True
            i += 1
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print userinvitations')
    if orderByList:
        orderBy = ' '.join(orderByList)
    else:
        orderBy = None
    gam.printGettingAllItems('User Invitations', filter_)
    page_message = gapi.got_total_items_msg('User Invitations', '...\n')
    invitations = gapi.get_all_pages(svc.customers().userinvitations(),
                                     'list',
                                     'userInvitations',
                                     page_message=page_message,
                                     parent=customer,
                                     filter=filter_,
                                     orderBy=orderBy)
    for invitation in invitations:
        invitation['name'] = _reduce_name(invitation['name'])
        row = {}
        for key, val in invitation.items():
            if key not in titles:
                titles.append(key)
            row[key] = val
        rows.append(row)
    display.write_csv_file(rows, titles, 'User Invitations', todrive)
Exemplo n.º 13
0
def printResourceCalendars():
    cd = gapi_directory.build()
    todrive = False
    fieldsList = []
    fieldsTitles = {}
    titles = []
    csvRows = []
    query = None
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower()
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'query':
            query = sys.argv[i + 1]
            i += 2
        elif myarg == 'allfields':
            fieldsList = []
            fieldsTitles = {}
            titles = []
            for field in RESCAL_ALLFIELDS:
                display.add_field_to_csv_file(field,
                                              RESCAL_ARGUMENT_TO_PROPERTY_MAP,
                                              fieldsList, fieldsTitles, titles)
            i += 1
        elif myarg in RESCAL_ARGUMENT_TO_PROPERTY_MAP:
            display.add_field_to_csv_file(myarg,
                                          RESCAL_ARGUMENT_TO_PROPERTY_MAP,
                                          fieldsList, fieldsTitles, titles)
            i += 1
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print resources')
    if not fieldsList:
        for field in RESCAL_DFLTFIELDS:
            display.add_field_to_csv_file(field,
                                          RESCAL_ARGUMENT_TO_PROPERTY_MAP,
                                          fieldsList, fieldsTitles, titles)
    fields = f'nextPageToken,items({",".join(set(fieldsList))})'
    if 'buildingId' in fieldsList:
        display.add_field_to_csv_file('buildingName',
                                      {'buildingName': ['buildingName',]},
                                      fieldsList, fieldsTitles, titles)
    gam.printGettingAllItems('Resource Calendars', None)
    page_message = gapi.got_total_items_first_last_msg('Resource Calendars')
    resources = gapi.get_all_pages(cd.resources().calendars(),
                                   'list',
                                   'items',
                                   page_message=page_message,
                                   message_attribute='resourceId',
                                   customer=GC_Values[GC_CUSTOMER_ID],
                                   query=query,
                                   fields=fields)
    for resource in resources:
        if 'featureInstances' in resource:
            features = [a_feature['feature']['name'] for \
                a_feature in resource['featureInstances']]
            resource['featureInstances'] = ','.join(features)
        if 'buildingId' in resource:
            resource['buildingName'] = getBuildingNameById(
                cd, resource['buildingId'])
            resource['buildingId'] = f'id:{resource["buildingId"]}'
        resUnit = {}
        for field in fieldsList:
            resUnit[fieldsTitles[field]] = resource.get(field, '')
        csvRows.append(resUnit)
    display.sort_csv_titles(['resourceId', 'resourceName', 'resourceEmail'],
                            titles)
    display.write_csv_file(csvRows, titles, 'Resources', todrive)
Exemplo n.º 14
0
def print_():
    cd = gapi_directory.build()
    todrive = False
    titles = []
    csvRows = []
    fields = None
    projection = orderBy = sortOrder = None
    queries = [None]
    delimiter = ' '
    listLimit = 1
    appsLimit = -1
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['query', 'queries']:
            queries = gam.getQueries(myarg, sys.argv[i + 1])
            i += 2
        elif myarg == 'delimiter':
            delimiter = sys.argv[i + 1]
            i += 2
        elif myarg == 'listlimit':
            listLimit = gam.getInteger(sys.argv[i + 1], myarg, minVal=-1)
            i += 2
        elif myarg == 'appslimit':
            appsLimit = gam.getInteger(sys.argv[i + 1], myarg, minVal=-1)
            i += 2
        elif myarg == 'fields':
            fields = f'nextPageToken,mobiledevices({sys.argv[i+1]})'
            i += 2
        elif myarg == 'orderby':
            orderBy = sys.argv[i + 1].lower()
            validOrderBy = [
                'deviceid', 'email', 'lastsync', 'model', 'name', 'os',
                'status', 'type'
            ]
            if orderBy not in validOrderBy:
                controlflow.expected_argument_exit('orderby',
                                                   ', '.join(validOrderBy),
                                                   orderBy)
            if orderBy == 'lastsync':
                orderBy = 'lastSync'
            elif orderBy == 'deviceid':
                orderBy = 'deviceId'
            i += 2
        elif myarg in SORTORDER_CHOICES_MAP:
            sortOrder = SORTORDER_CHOICES_MAP[myarg]
            i += 1
        elif myarg in PROJECTION_CHOICES_MAP:
            projection = PROJECTION_CHOICES_MAP[myarg]
            i += 1
        else:
            controlflow.invalid_argument_exit(sys.argv[i], 'gam print mobile')
    for query in queries:
        gam.printGettingAllItems('Mobile Devices', query)
        page_message = gapi.got_total_items_msg('Mobile Devices', '...\n')
        all_mobile = gapi.get_all_pages(cd.mobiledevices(),
                                        'list',
                                        'mobiledevices',
                                        page_message=page_message,
                                        customerId=GC_Values[GC_CUSTOMER_ID],
                                        query=query,
                                        projection=projection,
                                        fields=fields,
                                        orderBy=orderBy,
                                        sortOrder=sortOrder)
        for mobile in all_mobile:
            row = {}
            for attrib in mobile:
                if attrib in ['kind', 'etag']:
                    continue
                if attrib in ['name', 'email', 'otherAccountsInfo']:
                    if attrib not in titles:
                        titles.append(attrib)
                    if listLimit > 0:
                        row[attrib] = delimiter.join(
                            mobile[attrib][0:listLimit])
                    elif listLimit == 0:
                        row[attrib] = delimiter.join(mobile[attrib])
                elif attrib == 'applications':
                    if appsLimit >= 0:
                        if attrib not in titles:
                            titles.append(attrib)
                        applications = []
                        j = 0
                        for app in mobile[attrib]:
                            j += 1
                            if appsLimit and (j > appsLimit):
                                break
                            appDetails = []
                            for field in [
                                    'displayName', 'packageName', 'versionName'
                            ]:
                                appDetails.append(app.get(field, '<None>'))
                            appDetails.append(
                                str(app.get('versionCode', '<None>')))
                            permissions = app.get('permission', [])
                            if permissions:
                                appDetails.append('/'.join(permissions))
                            else:
                                appDetails.append('<None>')
                            applications.append('-'.join(appDetails))
                        row[attrib] = delimiter.join(applications)
                else:
                    if attrib not in titles:
                        titles.append(attrib)
                    if attrib == 'deviceId':
                        row[attrib] = mobile[attrib].encode(
                            'unicode-escape').decode(UTF8)
                    elif attrib == 'securityPatchLevel' and int(
                            mobile[attrib]):
                        row[attrib] = utils.formatTimestampYMDHMS(
                            mobile[attrib])
                    else:
                        row[attrib] = mobile[attrib]
            csvRows.append(row)
    display.sort_csv_titles(
        ['resourceId', 'deviceId', 'serialNumber', 'name', 'email', 'status'],
        titles)
    display.write_csv_file(csvRows, titles, 'Mobile', todrive)
Exemplo n.º 15
0
def print_():
    ci = gapi_cloudidentity.build()
    i = 3
    members = membersCountOnly = managers = managersCountOnly = owners = ownersCountOnly = False
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    aliasDelimiter = ' '
    memberDelimiter = '\n'
    todrive = False
    titles = []
    csvRows = []
    roles = []
    sortHeaders = False
    while i < len(sys.argv):
        myarg = sys.argv[i].lower()
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'delimiter':
            aliasDelimiter = memberDelimiter = sys.argv[i + 1]
            i += 2
        elif myarg == 'sortheaders':
            sortHeaders = True
            i += 1
        elif myarg in ['members', 'memberscount']:
            roles.append(ROLE_MEMBER)
            members = True
            if myarg == 'memberscount':
                membersCountOnly = True
            i += 1
        elif myarg in ['owners', 'ownerscount']:
            roles.append(ROLE_OWNER)
            owners = True
            if myarg == 'ownerscount':
                ownersCountOnly = True
            i += 1
        elif myarg in ['managers', 'managerscount']:
            roles.append(ROLE_MANAGER)
            managers = True
            if myarg == 'managerscount':
                managersCountOnly = True
            i += 1
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print cigroups')
    if roles:
        if members:
            display.add_titles_to_csv_file([
                'MembersCount',
            ], titles)
            if not membersCountOnly:
                display.add_titles_to_csv_file([
                    'Members',
                ], titles)
        if managers:
            display.add_titles_to_csv_file([
                'ManagersCount',
            ], titles)
            if not managersCountOnly:
                display.add_titles_to_csv_file([
                    'Managers',
                ], titles)
        if owners:
            display.add_titles_to_csv_file([
                'OwnersCount',
            ], titles)
            if not ownersCountOnly:
                display.add_titles_to_csv_file([
                    'Owners',
                ], titles)
    gam.printGettingAllItems('Groups', None)
    page_message = gapi.got_total_items_first_last_msg('Groups')
    entityList = gapi.get_all_pages(ci.groups(),
                                    'list',
                                    'groups',
                                    page_message=page_message,
                                    message_attribute=['groupKey', 'id'],
                                    parent=parent,
                                    srcview='FULL',
                                    pageSize=500)
    i = 0
    count = len(entityList)
    for groupEntity in entityList:
        i += 1
        groupEmail = groupEntity['groupKey']['id']
        group = utils.flatten_json(groupEntity)
        for a_key in group:
            if a_key not in titles:
                titles.append(a_key)
        groupKey_id = groupEntity['name']
        if roles:
            sys.stderr.write(
                f' Getting {roles} for {groupEmail}{gam.currentCountNL(i, count)}'
            )
            page_message = gapi.got_total_items_first_last_msg('Members')
            validRoles, listRoles, listFields = gam._getRoleVerification(
                roles, 'nextPageToken,members(email,id,role)')
            groupMembers = gapi.get_all_pages(ci.groups().memberships(),
                                              'list',
                                              'memberships',
                                              page_message=page_message,
                                              message_attribute='email',
                                              soft_errors=True,
                                              groupKey_id=groupKey_id,
                                              view='BASIC')
            if members:
                membersList = []
                membersCount = 0
            if managers:
                managersList = []
                managersCount = 0
            if owners:
                ownersList = []
                ownersCount = 0
            for member in groupMembers:
                member_email = member['memberKey']['id']
                role = get_single_role(member.get('roles'))
                if not validRoles or role in validRoles:
                    if role == ROLE_MEMBER:
                        if members:
                            membersCount += 1
                            if not membersCountOnly:
                                membersList.append(member_email)
                    elif role == ROLE_MANAGER:
                        if managers:
                            managersCount += 1
                            if not managersCountOnly:
                                managersList.append(member_email)
                    elif role == ROLE_OWNER:
                        if owners:
                            ownersCount += 1
                            if not ownersCountOnly:
                                ownersList.append(member_email)
                    elif members:
                        membersCount += 1
                        if not membersCountOnly:
                            membersList.append(member_email)
            if members:
                group['MembersCount'] = membersCount
                if not membersCountOnly:
                    group['Members'] = memberDelimiter.join(membersList)
            if managers:
                group['ManagersCount'] = managersCount
                if not managersCountOnly:
                    group['Managers'] = memberDelimiter.join(managersList)
            if owners:
                group['OwnersCount'] = ownersCount
                if not ownersCountOnly:
                    group['Owners'] = memberDelimiter.join(ownersList)
        csvRows.append(group)
    if sortHeaders:
        display.sort_csv_titles([
            'Email',
        ], titles)
    display.write_csv_file(csvRows, titles, 'Groups', todrive)
Exemplo n.º 16
0
def print_members():
    ci = gapi_cloudidentity.build()
    todrive = False
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    roles = []
    titles = ['group']
    csvRows = []
    groups_to_get = []
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['role', 'roles']:
            for role in sys.argv[i + 1].lower().replace(',', ' ').split():
                if role in GROUP_ROLES_MAP:
                    roles.append(GROUP_ROLES_MAP[role])
                else:
                    controlflow.system_error_exit(
                        2,
                        f'{role} is not a valid role for "gam print group-members {myarg}"'
                    )
            i += 2
        elif myarg in ['cigroup', 'cigroups']:
            group_email = gam.normalizeEmailAddressOrUID(sys.argv[i + 1])
            groups_to_get = [group_email]
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print cigroup-members')
    if not groups_to_get:
        gam.printGettingAllItems('Groups', None)
        page_message = gapi.got_total_items_first_last_msg('Groups')
        groups_to_get = gapi.get_all_pages(
            ci.groups(),
            'list',
            'groups',
            message_attribute=['groupKey', 'id'],
            page_message=page_message,
            parent=parent,
            view='BASIC',
            pageSize=1000,
            fields='nextPageToken,groups(groupKey(id))')
        groups_to_get = [group['groupKey']['id'] for group in groups_to_get]
    i = 0
    count = len(groups_to_get)
    for group_email in groups_to_get:
        i += 1

        sys.stderr.write(
            f'Getting members for {group_email}{gam.currentCountNL(i, count)}')
        group_id = group_email_to_id(ci, group_email)
        print(f'Getting members of cigroup {group_email}...')
        page_message = f' {gapi.got_total_items_first_last_msg("Members")}'
        group_members = gapi.get_all_pages(
            ci.groups().memberships(),
            'list',
            'memberships',
            soft_errors=True,
            parent=group_id,
            view='FULL',
            pageSize=500,
            page_message=page_message,
            message_attribute=['memberKey', 'id'])
        #fields='nextPageToken,memberships(memberKey,roles,createTime,updateTime)')
        if roles:
            group_members = filter_members_to_roles(group_members, roles)
        for member in group_members:
            # reduce role to a single value
            member['role'] = get_single_role(member.pop('roles'))
            member = utils.flatten_json(member)
            for title in member:
                if title not in titles:
                    titles.append(title)
            member['group'] = group_email
            csvRows.append(member)
    display.write_csv_file(csvRows, titles, 'Group Members', todrive)
Exemplo n.º 17
0
def printAppDevices():
    cm = build()
    customer = _get_customerid()
    todrive = False
    titles = CHROME_APP_DEVICES_TITLES
    csvRows = []
    orgunit = None
    appId = None
    appType = None
    startDate = None
    endDate = None
    pfilter = None
    orderBy = None
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['ou', 'org', 'orgunit']:
            orgunit = _get_orgunit(sys.argv[i + 1])
            i += 2
        elif myarg == 'appid':
            appId = sys.argv[i + 1]
            i += 2
        elif myarg == 'apptype':
            appType = sys.argv[i + 1].lower().replace('_', '')
            if appType not in CHROME_APP_DEVICES_APPTYPE_CHOICE_MAP:
                controlflow.expected_argument_exit(
                    'orderby',
                    ', '.join(CHROME_APP_DEVICES_APPTYPE_CHOICE_MAP), appType)
            appType = CHROME_APP_DEVICES_APPTYPE_CHOICE_MAP[appType]
            i += 2
        elif myarg in CROS_START_ARGUMENTS:
            startDate = _getFilterDate(sys.argv[i +
                                                1]).strftime(YYYYMMDD_FORMAT)
            i += 2
        elif myarg in CROS_END_ARGUMENTS:
            endDate = _getFilterDate(sys.argv[i + 1]).strftime(YYYYMMDD_FORMAT)
            i += 2
        elif myarg == 'orderby':
            orderBy = sys.argv[i + 1].lower().replace('_', '')
            if orderBy not in CHROME_APP_DEVICES_ORDERBY_CHOICE_MAP:
                controlflow.expected_argument_exit(
                    'orderby',
                    ', '.join(CHROME_APP_DEVICES_ORDERBY_CHOICE_MAP), orderBy)
            orderBy = CHROME_APP_DEVICES_ORDERBY_CHOICE_MAP[orderBy]
            i += 2
        else:
            msg = f'{myarg} is not a valid argument to "gam print chromeappdevices"'
            controlflow.system_error_exit(3, msg)
    if not appId:
        controlflow.system_error_exit(3, 'You must specify an appid')
    if not appType:
        controlflow.system_error_exit(3, 'You must specify an apptype')
    if endDate:
        pfilter = f'last_active_date<={endDate}'
    if startDate:
        if pfilter:
            pfilter += ' AND '
        else:
            pfilter = ''
        pfilter += f'last_active_date>={startDate}'
    if orgunit:
        orgUnitPath = gapi_directory_orgunits.orgunit_from_orgunitid(
            orgunit, None)
        titles.append('orgUnitPath')
    else:
        orgUnitPath = '/'
    gam.printGettingAllItems('Chrome Installed Application Devices', pfilter)
    page_message = gapi.got_total_items_msg(
        'Chrome Installed Application Devices', '...\n')
    devices = gapi.get_all_pages(cm.customers().reports(),
                                 'findInstalledAppDevices',
                                 'devices',
                                 page_message=page_message,
                                 appId=appId,
                                 appType=appType,
                                 customer=customer,
                                 orgUnitId=orgunit,
                                 filter=pfilter,
                                 orderBy=orderBy)
    for device in devices:
        if orgunit:
            device['orgUnitPath'] = orgUnitPath
        device['appId'] = appId
        device['appType'] = appType
        csvRows.append(device)
    display.write_csv_file(csvRows, titles,
                           'Chrome Installed Application Devices', todrive)