Assets mit der Security Command Center API auflisten

Assets sind Google Cloud-Ressourcen einer Organisation, z. B. Compute Engine-Instanzen oder Cloud Storage-Buckets.

In diesem Leitfaden erfahren Sie, wie Sie mit Security Command Center-Clientbibliotheken auf die verworfene Einträge, die Security Command Center für die Assets in für ein Projekt oder eine Organisation.

Security Command Center speichert nur Einträge für einen Teil der Assets in Cloud Asset Inventory verwenden. Die vollständige Liste der Assets in Ihrer Umgebung Cloud Asset Inventory verwenden, um Assets aufzulisten.

Hier finden Sie weitere Informationen:

Berechtigungsebenen für IAM-Rollen

Die IAM-Rollen für Security Command Center können in der Organisation, Ordner- oder Projektebene. Ihre Fähigkeit, Ergebnisse, Assets, und Sicherheitsquellen hängen von der Zugriffsebene ab. Weitere Informationen über Security Command Center-Rollen finden Sie unter Zugriffssteuerung.

Hinweise

Bevor Sie eine Quelle einrichten, müssen Sie die folgenden Schritte ausführen:

Seitengröße

Alle Security Command Center-Listen-APIs sind paginiert. Jede Antwort gibt eine Seite mit Ergebnissen und ein Token zurück, um die nächste Seite zurückzugeben. Die Seitengröße kann konfiguriert werden. Die Standardseitengröße ist 10. Sie kann auf ein Minimum von 1 und maximal 1.000 festgelegt werden.

Ressourcentypen

Für das Attribut resourceType in Security Command Center gilt eine andere Namenskonvention als für Cloud Asset Inventory. Eine Liste der Ressourcentypformate finden Sie unter Unterstützte Asset-Typen in Security Command Center.

Alle Assets auflisten

Die folgenden Beispiele zeigen, wie alle Assets aufgelistet werden:

gcloud

Führen Sie den folgenden Befehl aus, um alle Assets in einem Projekt, einem Ordner oder einer Organisation aufzulisten: Befehl:

gcloud scc assets list PARENT_ID

Ersetzen Sie PARENT_ID durch einen der folgenden Werte:

  • Eine Organisations-ID im folgenden Format: ORGANIZATION_ID (nur die numerische ID)
  • Eine Ordner-ID im folgenden Format: folders/FOLDER_ID
  • Eine Projekt-ID im folgenden Format: projects/PROJECT_ID

Weitere Beispiele erhalten Sie mit dem folgenden Befehl:

 gcloud scc assets list --help

Beispiele in der Dokumentation finden Sie unter gcloud scc assets list.

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()
# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

# Call the API and print results.
asset_iterator = client.list_assets(request={"parent": parent})
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

Java

static ImmutableList<ListAssetsResult> listAssets(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder().setParent(organizationName.toString());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("All assets:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/api/iterator"
)

// listAllAssets prints every asset to w for orgID. orgID is the numeric
// Organization ID.
func listAllAssets(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent: fmt.Sprintf("organizations/%s", orgID),
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s\n", properties.ResourceType)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;
// Call the API with automatic pagination.
async function listAssets() {
  const [response] = await client.listAssets({parent: parent});
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      }`
    )
  );
}

listAssets();

Die Ausgabe für jedes Asset ist ein JSON-Objekt, das in etwa so aussieht:

asset:
  createTime: '2020-10-05T17:55:14.823Z'
  iamPolicy:
    policyBlob: '{"bindings":[{"role":"roles/owner","members":["serviceAccount:SERVICE_ACCOUNT@PROJECT_ID.iam.gserviceaccount.com","user:USER_EMAIL@gmail.com"]}]}'
  name: organizations/ORGANIZATION_ID/assets/ASSET_ID
  resourceProperties:
    createTime: '2020-10-05T17:36:17.915Z'
    lifecycleState: ACTIVE
    name: PROJECT_ID
    parent: '{"id":"ORGANIZATION_ID","type":"organization"}'
    projectId: PROJECT_ID
    projectNumber: 'PROJECT_NUMBER'
  securityCenterProperties:
    resourceDisplayName: PROJECT_ID
    resourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
    resourceOwners:
    - serviceAccount:SERVICE_ACCOUNT@PROJECT_ID.iam.gserviceaccount.com
    - user:USER_EMAIL@gmail.com
    resourceParent: //cloudresourcemanager.googleapis.com/organizations/ORGANIZATION_ID
    resourceParentDisplayName: ORGANIZATION_NAME
    resourceProject: //cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
    resourceProjectDisplayName: PROJECT_ID
    resourceType: google.cloud.resourcemanager.Project
  securityMarks:
    name: organizations/ORGANIZATION_ID/assets/ASSET_ID/securityMarks
  updateTime: '2020-10-05T17:55:14.823Z'

Assets filtern

Ein Projekt, ein Ordner oder eine Organisation kann viele Assets enthalten. Die vorherige werden in diesem Beispiel Filter, sodass alle Assets zurückgegeben werden. In Security Command Center können Sie Assetfilter verwenden, um Informationen zu bestimmten Assets abzurufen. Filter ähneln "where"-Klauseln in SQL-Anweisungen, außer dass sie statt für Spalten für die von der API zurückgegebenen Objekte gelten.

Die Beispielausgabe im vorherigen Beispiel zeigt einige Felder und Unterfelder sowie ihre Attribute, die in Asset-Filtern verwendet werden können. Security Command Center unterstützt vollständige JSON-Arrays und -Objekte als potenzielle Attributtypen. Sie können nach folgenden Kriterien filtern:

  • Arrayelemente
  • Vollständige JSON-Objekte mit partieller Stringübereinstimmung im Objekt
  • Untergeordnete JSON-Objekt-Felder

Unterfelder müssen Zahlen, Strings oder boolesche Werte sein und Filterausdrücke müssen die folgenden Vergleichsoperatoren verwenden:

  • Strings:
    • Vollständige Gleichheit =
    • Teilstring, der mit : übereinstimmt
  • Nummern:
    • Ungleichungen <, >, <=, >=
    • Gleichheit =
  • Boolesche Werte:
    • Gleichheit =

In den folgenden Beispielen werden Assets gefiltert:

gcloud

Verwenden Sie den folgenden Befehl, um Assets zu filtern:

gcloud scc assets list PARENT_ID --filter="FILTER"

Ersetzen Sie Folgendes:

  • FILTER durch den gewünschten Filter. Beispiel: gibt der folgende Filter nur Projektressourcen zurück:
    --filter="security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""
  • PARENT_ID durch einen der folgenden Werte: <ph type="x-smartling-placeholder">
      </ph>
    • Eine Organisations-ID im folgenden Format: ORGANIZATION_ID (nur die numerische ID)
    • Eine Ordner-ID im folgenden Format: folders/FOLDER_ID
    • Eine Projekt-ID im folgenden Format: projects/PROJECT_ID

Führen Sie den folgenden Befehl aus, um weitere Beispiele aufzurufen:

gcloud scc assets list --help

Beispiele in der Dokumentation finden Sie unter gcloud scc assets list.

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

project_filter = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)
# Call the API and print results.
asset_iterator = client.list_assets(
    request={"parent": parent, "filter": project_filter}
)
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

Java

static ImmutableList<ListAssetsResult> listAssetsWithFilter(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Project assets:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/api/iterator"
)

// listAllProjectAssets lists all current GCP project assets in orgID and
// prints out results to w. orgID is the numeric organization ID of interest.
func listAllProjectAssets(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.
	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent: fmt.Sprintf("organizations/%s", orgID),
		Filter: `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s\n", properties.ResourceType)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// const organizationId = "1234567777";
const orgName = client.organizationPath(organizationId);

// Call the API with automatic pagination.
// You can also list assets in a project/ folder. To do so, modify the parent
// value and filter condition.
async function listFilteredAssets() {
  const [response] = await client.listAssets({
    parent: orgName,
    filter:
      'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
  });
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      } ${result.stateChange}`
    )
  );
}

listFilteredAssets();

Zu einem bestimmten Zeitpunkt auflisten

Die vorherigen Beispiele zeigen, wie eine aktuelle Gruppe von Assets aufgelistet wird. Mit Security Command Center können Sie auch einen Verlauf der Assets ansehen. In den folgenden Beispielen wird der Status aller Assets zurückgegeben zu einem bestimmten Zeitpunkt geschaltet werden. Security Command Center unterstützt Millisekunden-Zeitlösungen.

gcloud

Verwenden Sie den folgenden Befehl, um Assets für einen bestimmten Zeitpunkt aufzulisten:

gcloud scc assets list PARENT_ID --read-time="READ_TIME"

Ersetzen Sie Folgendes:

  • READ_TIME durch den Zeitpunkt, zu dem Assets aufgelistet werden sollen. Verwenden Sie das folgende Format: YYYY-MM-DDThh:mm:ss.ffffffZ Beispiel:
    --read-time="2022-12-21T07:00:06.861Z"
    .
  • PARENT_ID durch einen der folgenden Werte: <ph type="x-smartling-placeholder">
      </ph>
    • Eine Organisations-ID im folgenden Format: ORGANIZATION_ID (nur die numerische ID)
    • Eine Projekt-ID im folgenden Format: projects/PROJECT_ID
    • Eine Ordner-ID im folgenden Format: folders/FOLDER_ID

Führen Sie den folgenden Befehl aus, um weitere Beispiele aufzurufen:

gcloud scc assets list --help

Beispiele in der Dokumentation finden Sie unter gcloud scc assets list.

Python

from datetime import datetime, timedelta, timezone

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

project_filter = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)

# Lists assets as of yesterday.
read_time = datetime.now(tz=timezone.utc) - timedelta(days=1)

# Call the API and print results.
asset_iterator = client.list_assets(
    request={"parent": parent, "filter": project_filter, "read_time": read_time}
)
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

Java

static ImmutableList<ListAssetsResult> listAssetsAsOfYesterday(
    OrganizationName organizationName, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    // Initialize the builder with the parent and filter
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");

    // Set read time to either the instant passed in or one day ago.
    asOf = MoreObjects.firstNonNull(asOf, Instant.now().minus(Duration.ofDays(1)));
    request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Projects:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
)

// listAllProjectAssets lists all GCP Projects in orgID at asOf time and prints
// out results to w. orgID is the numeric organization ID of interest.
func listAllProjectAssetsAtTime(w io.Writer, orgID string, asOf time.Time) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	// Convert the time to a Timestamp protobuf
	readTime, err := ptypes.TimestampProto(asOf)
	if err != nil {
		return fmt.Errorf("TimestampProto(%v): %w", asOf, err)
	}

	// You can also list assets in a project/ folder. To do so, modify the parent and
	// filter condition.
	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent:   fmt.Sprintf("organizations/%s", orgID),
		Filter:   `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
		ReadTime: readTime,
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s\n", properties.ResourceType)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;

const oneDayAgo = new Date();
oneDayAgo.setDate(oneDayAgo.getDate() - 1);

// Call the API with automatic pagination.
async function listAssetsAtTime() {
  const [response] = await client.listAssets({
    parent: parent,
    filter:
      'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
    // readTime must be in the form of a google.protobuf.Timestamp object
    // which takes seconds and nanoseconds.
    readTime: {
      seconds: Math.floor(oneDayAgo.getTime() / 1000),
      nanos: (oneDayAgo.getTime() % 1000) * 1e6,
    },
  });
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      }`
    )
  );
}

listAssetsAtTime();

Assets mit Statusänderungen auflisten

Mit Security Command Center können Sie ein Asset zu zwei Zeitpunkten vergleichen, um festzustellen, ob es im angegebenen Zeitraum hinzugefügt oder entfernt wurde oder vorhanden war. Die In den folgenden Beispielen werden Projekte, die unter READ_TIME vorhanden sind, mit einem früheren Projekt verglichen Zeitpunkt, der durch COMPARE_DURATION angegeben wird. COMPARE_DURATION wird in Sekunden angegeben.

Wenn COMPARE_DURATION festgelegt ist, wird das Attribut stateChange in den Ergebnissen der Auflistung von Assets mit einem der folgenden Werte aktualisiert:

  • ADDED: Das Asset war nicht zu Beginn von compareDuration, aber zu readTime vorhanden.
  • REMOVED: Das Asset war zu Beginn von compareDuration, aber nicht zu readTime vorhanden.
  • ACTIVE: Das Asset war sowohl am Anfang als auch am Ende des Zeitraums vorhanden, der durch compareDuration und readTime definiert ist.

gcloud

Verwenden Sie den folgenden Befehl, um den Status von Assets an zwei Punkten in Zeit:

gcloud scc assets list PARENT_ID \
    --filter="FILTER" \
    --read-time=READ_TIME \
    --compare-duration=COMPARE_DURATION

Ersetzen Sie Folgendes:

  • COMPARE_DURATION durch die Anzahl der Sekunden, definiert einen Zeitpunkt vor der in der --read-time-Flag. Beispiel:
    --compare-duration=84600s
    .
  • FILTER durch den gewünschten Filter. Beispiel: gibt der folgende Filter nur Projektressourcen zurück:
    --filter="security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""
  • PARENT_ID durch einen der folgenden Werte: <ph type="x-smartling-placeholder">
      </ph>
    • Eine Organisations-ID im folgenden Format: ORGANIZATION_ID (nur die numerische ID)
    • Eine Projekt-ID im folgenden Format: projects/PROJECT_ID
    • Eine Ordner-ID im folgenden Format: folders/FOLDER_ID
  • READ_TIME durch den Zeitpunkt, zu dem Assets aufgelistet werden sollen. Verwenden Sie im folgenden Format: YYYY-MM-DDThh:mm:ss.ffffffZ Hier einige Beispiele:
    --read-time="2022-12-21T07:00:06.861Z"
    Weitere Beispiele erhalten Sie mit dem folgenden Befehl:
gcloud scc assets list --help

Beispiele in der Dokumentation finden Sie unter gcloud scc assets list.

Python

from datetime import timedelta

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"
project_filter = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)

# List assets and their state change the last 30 days
compare_delta = timedelta(days=30)

# Call the API and print results.
asset_iterator = client.list_assets(
    request={
        "parent": parent,
        "filter": project_filter,
        "compare_duration": compare_delta,
    }
)
for i, asset in enumerate(asset_iterator):
    print(i, asset)

Java

static ImmutableList<ListAssetsResult> listAssetAndStatusChanges(
    OrganizationName organizationName, Duration timeSpan, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {

    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");
    request
        .getCompareDurationBuilder()
        .setSeconds(timeSpan.getSeconds())
        .setNanos(timeSpan.getNano());

    // Set read time to either the instant passed in or now.
    asOf = MoreObjects.firstNonNull(asOf, Instant.now());
    request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Projects:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
)

// listAllProjectAssetsAndStateChange lists all current GCP project assets in
// orgID and prints the projects and there change from a day ago out to w.
// orgID is the numeric // organization ID of interest.
func listAllProjectAssetsAndStateChanges(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent:          fmt.Sprintf("organizations/%s", orgID),
		Filter:          `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
		CompareDuration: ptypes.DurationProto(24 * time.Hour),
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s", properties.ResourceType)
		fmt.Fprintf(w, "State Change %s\n", result.StateChange)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;
// Call the API with automatic pagination.
async function listAssetsAndChanges() {
  const [response] = await client.listAssets({
    parent: parent,
    compareDuration: {seconds: 30 * /*Second in Day=*/ 86400, nanos: 0},
    filter:
      'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
  });
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      } ${result.stateChange}`
    )
  );
}

listAssetsAndChanges();

Beispiele für Filter

Im Folgenden finden Sie einige weitere nützliche Asset-Filter: Sie können AND und OR in Filtern verwenden, um Parameter zu kombinieren und Ergebnisse zu maximieren oder zu verfeinern.

Projekt-Assets mit einem bestimmten Inhaber finden

"security_center_properties.resource_type = \"google.cloud.resourcemanager.Project\" AND security_center_properties.resource_owners : \"$USER\""

$USER hat normalerweise das Format user:someone@domain.com. Für den Vergleich von user wird der Teilstringoperator : verwendet. Eine genaue Übereinstimmung ist nicht erforderlich.

Firewallregeln mit offenen HTTP-Ports

"security_center_properties.resource_type = \"google.compute.Firewall\" AND resource_properties.name =\"default-allow-http\""

Ressourcen, die zu bestimmten Projekten gehören

"security_center_properties.resource_parent = \"$PROJECT_1_NAME\" OR security_center_properties.resource_parent = \"$PROJECT_2_NAME\""

$PROJECT_1_NAME und $PROJECT_2_NAME sind Ressourcenkennungen in der Form //cloudresourcemanager.googleapis.com/projects/$PROJECT_ID, wobei $PROJECT_ID die Projektnummer ist. Ein vollständiges Beispiel wäre //cloudresourcemanager.googleapis.com/projects/100090906.

Compute Engine-Images suchen, deren Namen einen bestimmten String enthalten

Dieser Filter gibt Compute Engine-Images zurück, die einen Teilstring "Debia" enthalten:

"security_center_properties.resource_type = \"google.compute.Image\" AND resource_properties.name : \"Debia\""

Ressourcen, deren Attribute Schlüssel/Wert-Paare enthalten

Dieser Filter gibt Cloud Storage-Buckets zurück, bei denen bucketPolicyOnly deaktiviert ist. Der Wert von resourceProperties.iamConfiguration wird als String codiert. Mit dem Zeichen \ maskieren Sie Sonderzeichen in Strings, einschließlich des Operators : zwischen Schlüsselname und Wert.

"resourceProperties.iamConfiguration:"\"bucketPolicyOnly\"\:{\"enabled\"\:false""

Projekt-Assets suchen, die zu einem bestimmten Zeitpunkt oder vor einem bestimmten Zeitpunkt erstellt wurden

Diese Beispielfilter stimmen mit Assets überein, die am oder nach dem 18. Juli 2019 um 20:26:21 Uhr (GMT) erstellt wurden. Mit dem Filter create_time können Sie die Zeit in den folgenden Formaten und Typen angeben:

  • Unix-Zeit (in Millisekunden) als Ganzzahlliteral

    "create_time <= 1563481581000"
    
  • RFC 3339 als String-Literal

    "create_time <= \"2019-07-18T20:26:21+00:00\""
    

Assets aus Ergebnissen ausschließen

Wenn Sie ein Asset aus den Ergebnissen ausschließen möchten, fügen Sie vor einem Parameter ein --Zeichen ein. Der Vorgang ähnelt der Verwendung des NOT-Operators in einer SQL-Anweisung.

Dieser Filter gibt alle Projektressourcen außer Debia zurück:

"security_center_properties.resource_type = \"google.cloud.resourcemanager.Project\" AND -resource_properties.projectId = \"Debia\""

Nächste Schritte

Weitere Informationen über Auf Security Command Center über eine Clientbibliothek zugreifen