Répertorier les éléments par heure
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Montre comment répertorier les éléments à des moments précis.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[],[],null,["Demonstrates how to list assets for specific points in time\n\nExplore further\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Listing assets using the Security Command Center API](/security-command-center/docs/how-to-api-list-assets)\n\nCode sample \n\nGo\n\n\nTo authenticate to Security Command Center, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n \t\"time\"\n\n \tsecuritycenter \"cloud.google.com/go/securitycenter/apiv1\"\n \t\"cloud.google.com/go/securitycenter/apiv1/securitycenterpb\"\n \t\"github.com/golang/protobuf/ptypes\"\n \t\"google.golang.org/api/iterator\"\n )\n\n // listAllProjectAssets lists all GCP Projects in orgID at asOf time and prints\n // out results to w. orgID is the numeric organization ID of interest.\n func listAllProjectAssetsAtTime(w io.Writer, orgID string, asOf time.Time) error {\n \t// orgID := \"12321311\"\n \t// Instantiate a context and a security service client to make API calls.\n \tctx := context.Background()\n \tclient, err := securitycenter.https://cloud.google.com/go/docs/reference/cloud.google.com/go/securitycenter/latest/apiv1.html#cloud_google_com_go_securitycenter_apiv1_Client_NewClient(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"securitycenter.NewClient: %w\", err)\n \t}\n \tdefer client.https://cloud.google.com/go/docs/reference/cloud.google.com/go/securitycenter/latest/apiv1.html#cloud_google_com_go_securitycenter_apiv1_Client_Close() // Closing the client safely cleans up background resources.\n\n \t// Convert the time to a Timestamp protobuf\n \treadTime, err := ptypes.TimestampProto(asOf)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"TimestampProto(%v): %w\", asOf, err)\n \t}\n\n \t// You can also list assets in a project/ folder. To do so, modify the parent and\n \t// filter condition.\n \treq := &securitycenterpb.ListAssetsRequest{\n \t\t// Parent must be in one of the following formats:\n \t\t//\t\t\"organizations/{orgId}\"\n \t\t//\t\t\"projects/{projectId}\"\n \t\t//\t\t\"folders/{folderId}\"\n \t\tParent: fmt.Sprintf(\"organizations/%s\", orgID),\n \t\tFilter: `security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"`,\n \t\tReadTime: readTime,\n \t}\n\n \tassetsFound := 0\n \tit := client.ListAssets(ctx, req)\n \tfor {\n \t\tresult, err := it.Next()\n \t\tif err == iterator.Done {\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\treturn fmt.Errorf(\"ListAssets: %w\", err)\n \t\t}\n \t\tasset := result.Asset\n \t\tproperties := asset.SecurityCenterProperties\n \t\tfmt.Fprintf(w, \"Asset Name: %s,\", asset.Name)\n \t\tfmt.Fprintf(w, \"Resource Name %s,\", properties.ResourceName)\n \t\tfmt.Fprintf(w, \"Resource Type %s\\n\", properties.ResourceType)\n \t\tassetsFound++\n \t}\n \treturn nil\n }\n\nJava\n\n\nTo authenticate to Security Command Center, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n static ImmutableList\u003cListAssetsResult\u003e listAssetsAsOfYesterday(\n OrganizationName organizationName, Instant asOf) {\n try (SecurityCenterClient client = SecurityCenterClient.create()) {\n // Start setting up a request to search for all assets in an organization, project, or folder.\n //\n // Parent must be in one of the following formats:\n // OrganizationName organizationName = OrganizationName.of(\"organization-id\");\n // ProjectName projectName = ProjectName.of(\"project-id\");\n // FolderName folderName = FolderName.of(\"folder-id\");\n // Initialize the builder with the parent and filter\n ListAssetsRequest.Builder request =\n ListAssetsRequest.newBuilder()\n .setParent(organizationName.toString())\n .setFilter(\n \"security_center_properties.resource_type=\\\"google.cloud.resourcemanager.Project\\\"\");\n\n // Set read time to either the instant passed in or one day ago.\n asOf = MoreObjects.firstNonNull(asOf, Instant.now().minus(Duration.ofDays(1)));\n request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());\n\n // Call the API.\n ListAssetsPagedResponse response = client.listAssets(request.build());\n\n // This creates one list for all assets. If your organization has a large number of assets\n // this can cause out of memory issues. You can process them incrementally by returning\n // the Iterable returned response.iterateAll() directly.\n ImmutableList\u003cListAssetsResult\u003e results = ImmutableList.copyOf(response.iterateAll());\n System.out.println(\"Projects:\");\n System.out.println(results);\n return results;\n } catch (IOException e) {\n throw new RuntimeException(\"Couldn't create client.\", e);\n }\n }\n\nNode.js\n\n\nTo authenticate to Security Command Center, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Imports the Google Cloud client library.\n const {SecurityCenterClient} = require('https://cloud.google.com/nodejs/docs/reference/security-center/latest/overview.html');\n\n // Creates a new client.\n const client = new https://cloud.google.com/nodejs/docs/reference/security-center/latest/overview.html();\n // organizationId is the numeric ID of the organization.\n /*\n * TODO(developer): Uncomment the following lines\n */\n // parent: must be in one of the following formats:\n // `organizations/${organization_id}`\n // `projects/${project_id}`\n // `folders/${folder_id}`\n const parent = `organizations/${organizationId}`;\n\n const oneDayAgo = new Date();\n oneDayAgo.setDate(oneDayAgo.getDate() - 1);\n\n // Call the API with automatic pagination.\n async function listAssetsAtTime() {\n const [response] = await client.listAssets({\n parent: parent,\n filter:\n 'security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"',\n // readTime must be in the form of a google.protobuf.Timestamp object\n // which takes seconds and nanoseconds.\n readTime: {\n seconds: Math.floor(oneDayAgo.getTime() / 1000),\n nanos: (oneDayAgo.getTime() % 1000) * 1e6,\n },\n });\n let count = 0;\n Array.from(response).forEach(result =\u003e\n console.log(\n `${++count} ${result.asset.name} ${\n result.asset.securityCenterProperties.resourceName\n }`\n )\n );\n }\n\n listAssetsAtTime();\n\nPython\n\n\nTo authenticate to Security Command Center, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from datetime import datetime, timedelta, timezone\n\n from google.cloud import securitycenter\n\n client = securitycenter.SecurityCenterClient()\n\n # 'parent' must be in one of the following formats:\n # \"organizations/{organization_id}\"\n # \"projects/{project_id}\"\n # \"folders/{folder_id}\"\n parent = f\"organizations/{organization_id}\"\n\n project_filter = (\n \"security_center_properties.resource_type=\"\n + '\"google.cloud.resourcemanager.Project\"'\n )\n\n # Lists assets as of yesterday.\n read_time = datetime.now(tz=timezone.utc) - timedelta(days=1)\n\n # Call the API and print results.\n asset_iterator = client.https://cloud.google.com/python/docs/reference/securitycenter/latest/google.cloud.securitycenter_v1.services.security_center.SecurityCenterClient.html#google_cloud_securitycenter_v1_services_security_center_SecurityCenterClient_list_assets(\n request={\"parent\": parent, \"filter\": project_filter, \"read_time\": read_time}\n )\n for i, asset_result in enumerate(asset_iterator):\n print(i, asset_result)\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=securitycenter)."]]