列出作业

列出当前项目的所有 Cloud DLP 作业。

包含此代码示例的文档页面

如需查看上下文中使用的代码示例,请参阅以下文档:

代码示例

C#

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class JobsList
{
    public static PagedEnumerable<ListDlpJobsResponse, DlpJob> ListDlpJobs(string projectId, string filter, DlpJobType jobType)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.ListDlpJobs(new ListDlpJobsRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            Filter = filter,
            Type = jobType
        });

        // Uncomment to print jobs
        // foreach (var job in response)
        // {
        //     Console.WriteLine($"Job: {job.Name} status: {job.State}");
        // }

        return response;
    }
}

Go

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"google.golang.org/api/iterator"
	dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2"
)

// listJobs lists jobs matching the given optional filter and optional jobType.
func listJobs(w io.Writer, projectID, filter, jobType string) error {
	// projectID := "my-project-id"
	// filter := "`state` = FINISHED"
	// jobType := "RISK_ANALYSIS_JOB"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %v", err)
	}
	defer client.Close()

	// Create a configured request.
	req := &dlppb.ListDlpJobsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Filter: filter,
		Type:   dlppb.DlpJobType(dlppb.DlpJobType_value[jobType]),
	}
	// Send the request and iterate over the results.
	it := client.ListDlpJobs(ctx, req)
	for {
		j, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}
		fmt.Fprintf(w, "Job %v status: %v\n", j.GetName(), j.GetState())
	}
	return nil
}

Java

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.DlpJobType;
import com.google.privacy.dlp.v2.ListDlpJobsRequest;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;

public class JobsList {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    listJobs(projectId);
  }

  // Lists DLP jobs
  public static void listJobs(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Construct the request to be sent by the client.
      // For more info on filters and job types,
      // see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
      ListDlpJobsRequest listDlpJobsRequest =
          ListDlpJobsRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setFilter("state=DONE")
              .setType(DlpJobType.valueOf("INSPECT_JOB"))
              .build();

      // Send the request to list jobs and process the response
      DlpServiceClient.ListDlpJobsPagedResponse response =
          dlpServiceClient.listDlpJobs(listDlpJobsRequest);

      System.out.println("DLP jobs found:");
      for (DlpJob dlpJob : response.getPage().getValues()) {
        System.out.println(dlpJob.getName() + " -- " + dlpJob.getState());
      }
    }
  }
}

Node.js

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The filter expression to use
// For more information and filter syntax, see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
// const filter = `state=DONE`;

// The type of job to list (either 'INSPECT_JOB' or 'RISK_ANALYSIS_JOB')
// const jobType = 'INSPECT_JOB';
async function listJobs() {
  // Construct request for listing DLP scan jobs
  const request = {
    parent: `projects/${projectId}/locations/global`,
    filter: filter,
    type: jobType,
  };

  // Run job-listing request
  const [jobs] = await dlp.listDlpJobs(request);
  jobs.forEach(job => {
    console.log(`Job ${job.name} status: ${job.state}`);
  });
}

listJobs();

PHP

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

/**
 * List Data Loss Prevention API jobs corresponding to a given filter.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\DlpJob\JobState;
use Google\Cloud\Dlp\V2\DlpJobType;

/** Uncomment and populate these variables in your code */
// $callingProjectId = 'The project ID to run the API call under';
// $filter = 'The filter expression to use';

// Instantiate a client.
$dlp = new DlpServiceClient();

// The type of job to list (either 'INSPECT_JOB' or 'REDACT_JOB')
$jobType = DlpJobType::INSPECT_JOB;

// Run job-listing request
// For more information and filter syntax,
// @see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
$parent = "projects/$callingProjectId/locations/global";
$response = $dlp->listDlpJobs($parent, [
  'filter' => $filter,
  'type' => $jobType
]);

// Print job list
$jobs = $response->iterateAllElements();
foreach ($jobs as $job) {
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), $job->getState());
    $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();

    if ($job->getState() == JobState::DONE) {
        if (count($infoTypeStats) > 0) {
            foreach ($infoTypeStats as $infoTypeStat) {
                printf(
                    '  Found %s instance(s) of type %s' . PHP_EOL,
                    $infoTypeStat->getCount(),
                    $infoTypeStat->getInfoType()->getName()
                );
            }
        } else {
            print('  No findings.' . PHP_EOL);
        }
    }
}

Python

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

def list_dlp_jobs(project, filter_string=None, job_type=None):
    """Uses the Data Loss Prevention API to lists DLP jobs that match the
        specified filter in the request.
    Args:
        project: The project id to use as a parent resource.
        filter: (Optional) Allows filtering.
            Supported syntax:
            * Filter expressions are made up of one or more restrictions.
            * Restrictions can be combined by 'AND' or 'OR' logical operators.
            A sequence of restrictions implicitly uses 'AND'.
            * A restriction has the form of '<field> <operator> <value>'.
            * Supported fields/values for inspect jobs:
                - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED
                - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY
                - `trigger_name` - The resource name of the trigger that
                                   created job.
            * Supported fields for risk analysis jobs:
                - `state` - RUNNING|CANCELED|FINISHED|FAILED
            * The operator must be '=' or '!='.
            Examples:
            * inspected_storage = cloud_storage AND state = done
            * inspected_storage = cloud_storage OR inspected_storage = bigquery
            * inspected_storage = cloud_storage AND
                                  (state = done OR state = canceled)
        type: (Optional) The type of job. Defaults to 'INSPECT'.
            Choices:
            DLP_JOB_TYPE_UNSPECIFIED
            INSPECT_JOB: The job inspected content for sensitive data.
            RISK_ANALYSIS_JOB: The job executed a Risk Analysis computation.

    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Import the client library.
    import google.cloud.dlp

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Job type dictionary
    job_type_to_int = {
        "DLP_JOB_TYPE_UNSPECIFIED": google.cloud.dlp.DlpJobType.DLP_JOB_TYPE_UNSPECIFIED,
        "INSPECT_JOB": google.cloud.dlp.DlpJobType.INSPECT_JOB,
        "RISK_ANALYSIS_JOB": google.cloud.dlp.DlpJobType.RISK_ANALYSIS_JOB,
    }
    # If job type is specified, convert job type to number through enums.
    if job_type:
        job_type = job_type_to_int[job_type]

    # Call the API to get a list of jobs.
    response = dlp.list_dlp_jobs(
        request={"parent": parent, "filter": filter_string, "type_": job_type}
    )

    # Iterate over results.
    for job in response:
        print("Job: %s; status: %s" % (job.name, job.state.name))

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器