Пример #1
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)
Пример #2
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)
Пример #3
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)