Cloud DLP 用戶端程式庫

本頁將說明如何開始使用 Cloud Data Loss Prevention API 適用的 Cloud 用戶端程式庫。如要進一步瞭解 Cloud API 適用的用戶端程式庫 (包括舊版 Google API 用戶端程式庫),請參閱用戶端程式庫說明

Compute Engine、App Engine 彈性環境、Google Kubernetes Engine 和 Cloud Functions 支援本頁所述的 Cloud DLP 用戶端程式庫。App Engine 標準環境上的 Java 8 支援 Java 適用的 Cloud DLP 用戶端程式庫。

如果您在 App Engine 標準環境上使用 Java 7,或將 App Engine 標準環境與 Go、PHP 或 Python 搭配使用,請使用 REST 介面存取 Cloud DLP。

安裝用戶端程式庫

C#

詳情請參閱設定 C# 開發環境的說明。如要建構及執行範例,請使用 Visual Studio 2015 以上版本,開啟解決方案檔案 (Dlp.sln) 並建構範例。

詳情請參閱 README

Go

go get -u github.com/GoogleCloudPlatform/golang-samples/dlp

Java

詳情請參閱設定 Java 開發環境一文。 如果您使用的是 Maven,請在 pom.xml 檔案中新增以下指令:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-dlp</artifactId>
    <version></version>
</dependency>

如果您是使用 Gradle,請將以下指令加入依附元件:

compile group: 'com.google.cloud', name: 'google-cloud-dlp', version: ''

Node.js

如需相關詳細資訊,請參閱設定 Node.js 開發環境的說明。
npm install --save @google-cloud/dlp

PHP

composer require google/cloud-dlp

Python

詳情請參閱設定 Python 開發環境一文。
  1. 如果您沒有 pipvirtualenv,請先安裝這兩個程式。如需操作說明,您可以參閱 Google Cloud Platform 的 Python 開發環境設定指南
  2. 複製或下載 GitHub 上 Google Cloud Platform 的 Python 範例文件
  3. 建立 virtualenv。範例與 Python 2.7.x 和 3.4 及更新版本相容。
    $ virtualenv env
    $ source env/bin/activate
  4. 從已複製或解壓縮的「Google Cloud Platform 的 Python 範例文件」目錄下的 dlp 目錄,安裝執行範例所需的依附元件。
    $ pip install -r requirements.txt

Ruby

如需相關詳細資訊,請參閱設定 Ruby 開發環境的說明。
gem install google-api-client

設定驗證

如要執行用戶端程式庫,您必須先建立服務帳戶並設定環境變數以設定驗證。請完成下列步驟來設定驗證方法。如需相關詳細資訊,請參閱 GCP 驗證說明文件

GCP 主控台

  1. 在 GCP 主控台中,前往「Create service account key」(建立服務帳戶金鑰) 頁面。

    前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面
  2. 從 [Service account] (服務帳戶) 清單中選取 [New service account] (新增服務帳戶)
  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
  4. 從 [Role] (角色) 清單中,選取 [Project] (專案) > [Owner] (擁有者)

    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。以後您可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  5. 點選 [建立]。一個包含您金鑰的 JSON 檔案會下載到電腦中。

指令列

您可以使用本機電腦上的 Cloud SDK,或在 Cloud Shell 內執行下列指令。

  1. 建立服務帳戶。將 [NAME] 換成服務帳戶的名稱。

    gcloud iam service-accounts create [NAME]
  2. 向服務帳戶授予權限。用您的專案 ID 取代 [PROJECT_ID]

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。您稍後可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  3. 產生金鑰檔案。用金鑰檔案的名稱取代 [FILE_NAME]

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

設定環境變數 GOOGLE_APPLICATION_CREDENTIALS 來為應用程式程式碼提供驗證憑證。 將 [PATH] 改成包含您的服務帳戶金鑰的 JSON 檔案路徑,並將 [FILE_NAME] 改成檔案名稱。 此變數僅適用於您目前的殼層工作階段,所以如果您開啟新的工作階段,請再次設定變數。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

使用命令提示字元:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

使用用戶端程式庫

以下範例顯示如何使用用戶端程式庫。

Go

func main() {
	ctx := context.Background()

	projectID := "PROJECT_ID"

	// Creates a DLP client.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		log.Fatalf("error creating DLP client: %v", err)
	}

	// The string to inspect.
	input := "Robert Frost"

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_POSSIBLE

	// The maximum number of findings to report (0 = server maximum).
	maxFindings := int32(0)

	// Whether to include the matching string.
	includeQuote := true

	// The infoTypes of information to match.
	infoTypes := []*dlppb.InfoType{
		{
			Name: "PERSON_NAME",
		},
		{
			Name: "US_STATE",
		},
	}

	// Construct item to inspect.
	item := &dlppb.ContentItem{
		DataItem: &dlppb.ContentItem_Value{
			Value: input,
		},
	}

	// Construct request.
	req := &dlppb.InspectContentRequest{
		Parent: "projects/" + projectID,
		InspectConfig: &dlppb.InspectConfig{
			InfoTypes:     infoTypes,
			MinLikelihood: minLikelihood,
			Limits: &dlppb.InspectConfig_FindingLimits{
				MaxFindingsPerRequest: maxFindings,
			},
			IncludeQuote: includeQuote,
		},
		Item: item,
	}

	// Run request.
	resp, err := client.InspectContent(ctx, req)
	if err != nil {
		log.Fatal(err)
	}
	findings := resp.GetResult().GetFindings()
	if len(findings) == 0 {
		fmt.Println("No findings.")
	}
	fmt.Println("Findings:")
	for _, f := range findings {
		if includeQuote {
			fmt.Println("\tQuote: ", f.GetQuote())
		}
		fmt.Println("\tInfo type: ", f.GetInfoType().GetName())
		fmt.Println("\tLikelihood: ", f.GetLikelihood())
	}
}

Java

public class QuickStart {

  /** Quick start to DLP API : inspects a given string for an InfoType. */
  public static void main(String[] args) throws Exception {

    // string to inspect
    String text = "His name was Robert Frost";

    // The minimum likelihood required before returning a match:
    // LIKELIHOOD_UNSPECIFIED, VERY_UNLIKELY, UNLIKELY, POSSIBLE, LIKELY, VERY_LIKELY, UNRECOGNIZED
    Likelihood minLikelihood = Likelihood.POSSIBLE;

    // The maximum number of findings to report (0 = server maximum)
    int maxFindings = 0;

    // The infoTypes of information to match
    List<InfoType> infoTypes =
        Arrays.asList(
            InfoType.newBuilder().setName("PERSON_NAME").build(),
            InfoType.newBuilder().setName("US_STATE").build());

    // Whether to include the matching string
    boolean includeQuote = true;

    // instantiate a client
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(maxFindings).build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .setIncludeQuote(includeQuote)
              .build();

      ByteContentItem byteContentItem =
          ByteContentItem.newBuilder()
              .setType(ByteContentItem.BytesType.TEXT_UTF8)
              .setData(ByteString.copyFromUtf8(text))
              .build();
      ContentItem contentItem = ContentItem.newBuilder().setByteItem(byteContentItem).build();

      String projectId = ServiceOptions.getDefaultProjectId();
      InspectContentRequest request =
          InspectContentRequest.newBuilder()
              .setParent(ProjectName.of(projectId).toString())
              .setInspectConfig(inspectConfig)
              .setItem(contentItem)
              .build();

      // Inspect the text for info types
      InspectContentResponse response = dlpServiceClient.inspectContent(request);

      InspectResult result = response.getResult();
      if (result.getFindingsCount() > 0) {
        System.out.println("Findings: ");
        for (Finding finding : result.getFindingsList()) {
          if (includeQuote) {
            System.out.print("\tQuote: " + finding.getQuote());
          }
          System.out.print("\tInfo type: " + finding.getInfoType().getName());
          System.out.println("\tLikelihood: " + finding.getLikelihood());
        }
      } else {
        System.out.println("No findings.");
      }
    } catch (Exception e) {
      System.out.println("Error in inspectString: " + e.getMessage());
    }
  }
}

Node.js

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

async function quickStart() {
  // Instantiates a client
  const dlp = new DLP.DlpServiceClient();

  // The string to inspect
  const string = 'Robert Frost';

  // The project ID to run the API call under
  const projectId = process.env.GCLOUD_PROJECT;

  // The minimum likelihood required before returning a match
  const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

  // The maximum number of findings to report (0 = server maximum)
  const maxFindings = 0;

  // The infoTypes of information to match
  const infoTypes = [{name: 'PERSON_NAME'}, {name: 'US_STATE'}];

  // Whether to include the matching string
  const includeQuote = true;

  // Construct item to inspect
  const item = {value: string};

  // Construct request
  const request = {
    parent: dlp.projectPath(projectId),
    inspectConfig: {
      infoTypes: infoTypes,
      minLikelihood: minLikelihood,
      limits: {
        maxFindingsPerRequest: maxFindings,
      },
      includeQuote: includeQuote,
    },
    item: item,
  };

  // Run request
  const [response] = await dlp.inspectContent(request);
  const findings = response.result.findings;
  if (findings.length > 0) {
    console.log(`Findings:`);
    findings.forEach(finding => {
      if (includeQuote) {
        console.log(`\tQuote: ${finding.quote}`);
      }
      console.log(`\tInfo type: ${finding.infoType.name}`);
      console.log(`\tLikelihood: ${finding.likelihood}`);
    });
  } else {
    console.log(`No findings.`);
  }
}
quickStart().catch(err => {
  console.error(`Error in inspectString: ${err.message || err}`);
});

PHP

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;

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

// The infoTypes of information to match
$usNameInfoType = (new InfoType())
    ->setName('PERSON_NAME');
$phoneNumberInfoType = (new InfoType())
    ->setName('PHONE_NUMBER');
$infoTypes = [$usNameInfoType, $phoneNumberInfoType];

// Set the string to inspect
$stringToInspect = 'Robert Frost';

// Only return results above a likelihood threshold, 0 for all
$minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

// Limit the number of findings, 0 for no limit
$maxFindings = 0;

// Whether to include the matching string in the response
$includeQuote = true;

// Specify finding limits
$limits = (new FindingLimits())
    ->setMaxFindingsPerRequest($maxFindings);

// Create the configuration object
$inspectConfig = (new InspectConfig())
    ->setMinLikelihood($minLikelihood)
    ->setLimits($limits)
    ->setInfoTypes($infoTypes)
    ->setIncludeQuote($includeQuote);

$content = (new ContentItem())
    ->setValue($stringToInspect);

$parent = $dlp->projectName(getEnv('GOOGLE_PROJECT_ID'));

// Run request
$response = $dlp->inspectContent($parent, array(
    'inspectConfig' => $inspectConfig,
    'item' => $content
));

$likelihoods = ['Unknown', 'Very unlikely', 'Unlikely', 'Possible',
                'Likely', 'Very likely'];

// Print the results
$findings = $response->getResult()->getFindings();
if (count($findings) == 0) {
    print('No findings.' . PHP_EOL);
} else {
    print('Findings:' . PHP_EOL);
    foreach ($findings as $finding) {
        if ($includeQuote) {
            print('  Quote: ' . $finding->getQuote() . PHP_EOL);
        }
        print('  Info type: ' . $finding->getInfoType()->getName() . PHP_EOL);
        $likelihoodString = $likelihoods[$finding->getLikelihood()];
        print('  Likelihood: ' . $likelihoodString . PHP_EOL);
    }
}

Python

# Import the client library
import google.cloud.dlp

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

# The string to inspect
content = 'Robert Frost'

# Construct the item to inspect.
item = {'value': content}

# The info types to search for in the content. Required.
info_types = [{'name': 'FIRST_NAME'}, {'name': 'LAST_NAME'}]

# The minimum likelihood to constitute a match. Optional.
min_likelihood = 'LIKELIHOOD_UNSPECIFIED'

# The maximum number of findings to report (0 = server maximum). Optional.
max_findings = 0

# Whether to include the matching string in the results. Optional.
include_quote = True

# Construct the configuration dictionary. Keys which are None may
# optionally be omitted entirely.
inspect_config = {
    'info_types': info_types,
    'min_likelihood': min_likelihood,
    'include_quote': include_quote,
    'limits': {'max_findings_per_request': max_findings},
}

# Convert the project id into a full resource id.
parent = dlp_client.project_path(project_id)

# Call the API.
response = dlp_client.inspect_content(parent, inspect_config, item)

# Print out the results.
if response.result.findings:
    for finding in response.result.findings:
        try:
            print('Quote: {}'.format(finding.quote))
        except AttributeError:
            pass
        print('Info type: {}'.format(finding.info_type.name))
        # Convert likelihood value to string respresentation.
        likelihood = (google.cloud.dlp.types.Finding.DESCRIPTOR
                      .fields_by_name['likelihood']
                      .enum_type.values_by_number[finding.likelihood]
                      .name)
        print('Likelihood: {}'.format(likelihood))
else:
    print('No findings.')

其他資源

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Data Loss Prevention