列出内置 infoType 检测器

InfoType 是指敏感数据类型。敏感数据保护支持内置和自定义的 infoType。您可以在 infoTypes 参考文档中查看所有内置 infoType,也可以使用 DLP API 以编程方式列出所有内置 infoType。

infoTypes.list 方法列出了敏感数据保护中当前支持的所有内置 infoType。每个 infoType 都包含以下信息:

  • infoType 标识符 (ID),即 infoType 的内部名称。
  • infoType 显示名,即直观易懂的 infoType 名称。
  • 检查风险分析操作是否支持相应的 infoType。

代码示例

要列出所有内置 infoType 检测器,请执行以下操作:

控制台

  1. 在 Google Cloud 控制台中,打开“敏感数据保护”。

    前往 Sensitive Data Protection 界面

  2. 点击配置标签页,然后点击 InfoType

  3. 系统即会显示包含所有内置 infoType 检测器的表格。

C#

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using System;
using Google.Cloud.Dlp.V2;

public class InfoTypesList
{
    public static ListInfoTypesResponse ListInfoTypes(string languageCode, string filter)
    {
        var dlp = DlpServiceClient.Create();
        var response = dlp.ListInfoTypes(
            new ListInfoTypesRequest
            {
                LanguageCode = languageCode,
                Filter = filter
            });

        // Uncomment to print infotypes
        // Console.WriteLine("Info Types:");
        // foreach (var InfoType in response.InfoTypes)
        // {
        //     Console.WriteLine($"\t{InfoType.Name} ({InfoType.DisplayName})");
        // }

        return response;
    }
}

Go

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// infoTypes returns the info types in the given language and matching the given filter.
func infoTypes(w io.Writer, languageCode, filter string) error {
	// languageCode := "en-US"
	// filter := "supported_by=INSPECT"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	req := &dlppb.ListInfoTypesRequest{
		LanguageCode: languageCode,
		Filter:       filter,
	}
	resp, err := client.ListInfoTypes(ctx, req)
	if err != nil {
		return fmt.Errorf("ListInfoTypes: %w", err)
	}
	for _, it := range resp.GetInfoTypes() {
		fmt.Fprintln(w, it.GetName())
	}
	return nil
}

Java

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.InfoTypeDescription;
import com.google.privacy.dlp.v2.ListInfoTypesRequest;
import com.google.privacy.dlp.v2.ListInfoTypesResponse;
import java.io.IOException;

public class InfoTypesList {

  public static void main(String[] args) throws IOException {
    listInfoTypes();
  }

  // Lists the types of sensitive information the DLP API supports.
  public static void listInfoTypes() 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 dlpClient = DlpServiceClient.create()) {

      // Construct the request to be sent by the client
      ListInfoTypesRequest listInfoTypesRequest =
          ListInfoTypesRequest.newBuilder()
              // Only return infoTypes supported by certain parts of the API.
              // Supported filters are "supported_by=INSPECT" and "supported_by=RISK_ANALYSIS"
              // Defaults to "supported_by=INSPECT"
              .setFilter("supported_by=INSPECT")
              // BCP-47 language code for localized infoType friendly names.
              // Defaults to "en_US"
              .setLanguageCode("en-US")
              .build();

      // Use the client to send the API request.
      ListInfoTypesResponse response = dlpClient.listInfoTypes(listInfoTypesRequest);

      // Parse the response and process the results
      System.out.println("Infotypes found:");
      for (InfoTypeDescription infoTypeDescription : response.getInfoTypesList()) {
        System.out.println("Name : " + infoTypeDescription.getName());
        System.out.println("Display name : " + infoTypeDescription.getDisplayName());
      }
    }
  }
}

Node.js

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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 BCP-47 language code to use, e.g. 'en-US'
// const languageCode = 'en-US';

// The filter to use
// const filter = 'supported_by=INSPECT'

async function listInfoTypes() {
  const [response] = await dlp.listInfoTypes({
    languageCode: languageCode,
    filter: filter,
  });
  const infoTypes = response.infoTypes;
  console.log('Info types:');
  infoTypes.forEach(infoType => {
    console.log(`\t${infoType.name} (${infoType.displayName})`);
  });
}

listInfoTypes();

PHP

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\ListInfoTypesRequest;

/**
 * Lists all Info Types for the Data Loss Prevention (DLP) API.
 *
 * @param string $filter        (Optional) filter to use
 * @param string $languageCode  (Optional) language code, empty for 'en-US'
 */
function list_info_types(string $filter = '', string $languageCode = ''): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run request
    $listInfoTypesRequest = (new ListInfoTypesRequest())
        ->setLanguageCode($languageCode)
        ->setFilter($filter);
    $response = $dlp->listInfoTypes($listInfoTypesRequest);

    // Print the results
    print('Info Types:' . PHP_EOL);
    foreach ($response->getInfoTypes() as $infoType) {
        printf(
            '  %s (%s)' . PHP_EOL,
            $infoType->getDisplayName(),
            $infoType->getName()
        );
    }
}

Python

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import Optional

import google.cloud.dlp


def list_info_types(
    language_code: Optional[str] = None, result_filter: Optional[str] = None
) -> None:
    """List types of sensitive information within a category.
    Args:
        language_code: The BCP-47 language code to use, e.g. 'en-US'.
        result_filter: An optional filter to only return info types supported by
                certain parts of the API. Defaults to "supported_by=INSPECT".
    Returns:
        None; the response from the API is printed to the terminal.
    """

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

    # Make the API call.
    response = dlp.list_info_types(
        request={"parent": language_code, "filter": result_filter}
    )

    # Print the results to the console.
    print("Info types:")
    for info_type in response.info_types:
        print(
            "{name}: {display_name}".format(
                name=info_type.name, display_name=info_type.display_name
            )
        )

REST

JSON 输入:

GET https://dlp.googleapis.com/v2/infoTypes?key={YOUR_API_KEY}

上面的请求在发送到指定的端点后,将会返回一个格式如下且包含所有预定义检测器的列表,其中:

  • [INFOTYPE-NAME] 表示 infoType 检测器的名称
  • [INFOTYPE-DISPLAY-NAME] 表示检测器的显示名
  • "supportedBy" 设为 "INSPECT""RISK_ANALYSIS" 或同时设为这两者,具体取决于检查风险分析操作是否支持相应的检测器
  • [INFOTYPE-DESCRIPTION] 表示检测器说明。

JSON 输出:

{
  "infoTypes":[
    {
      "name":"[INFOTYPE-NAME]",
      "displayName":"[INFOTYPE-DISPLAY-NAME]",
      "supportedBy":[
        "INSPECT"
      ],
      "description":"[INFOTYPE-DESCRIPTION]"
    },
    ...
  ]
}

API Explorer

您可以使用 API Explorer 列出 infoType 检测器:

  1. 点击以下按钮,在 infoTypes.list 方法的参考页面上转到 API Explorer:

    打开 API Explorer

  2. 取消选中 Google OAuth 2.0

  3. 点击执行

API Explorer 即会向敏感数据保护功能发送请求,而后者会传回一个包含所有受支持的 infoType 检测器的 JSON 对象。