예제 #1
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)
예제 #2
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)
예제 #3
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)