

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用的代码示 CloudTrail 例 AWS SDKs
<a name="cloudtrail_code_examples"></a>

以下代码示例向您展示了如何 AWS CloudTrail 使用 AWS 软件开发套件 (SDK)。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

**更多资源**
+  **[ CloudTrail 开发者指南](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html)** —有关的更多信息 CloudTrail.
+ **[CloudTrail API 参考](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)**-有关所有可用 CloudTrail 操作的详细信息。
+ **[AWS 开发者中心](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** — 您可以按类别或全文搜索筛选的代码示例。
+ **[AWS SDK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 包含首选语言完整代码的 GitHub 存储库。包括有关设置和运行代码的说明。

**Contents**
+ [基本功能](cloudtrail_code_examples_basics.md)
  + [操作](cloudtrail_code_examples_actions.md)
    + [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
    + [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
    + [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
    + [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
    + [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
    + [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
    + [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
    + [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
    + [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
    + [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# 使用的基本示 CloudTrail 例 AWS SDKs
<a name="cloudtrail_code_examples_basics"></a>

以下代码示例说明如何使用 with 的基础 AWS CloudTrail 知识 AWS SDKs。

**Contents**
+ [操作](cloudtrail_code_examples_actions.md)
  + [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
  + [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
  + [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
  + [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
  + [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
  + [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
  + [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
  + [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
  + [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
  + [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# CloudTrail 使用的操作 AWS SDKs
<a name="cloudtrail_code_examples_actions"></a>

以下代码示例演示了如何使用执行单个 CloudTrail操作 AWS SDKs。每个示例都包含一个指向的链接 GitHub，您可以在其中找到有关设置和运行代码的说明。

 以下示例仅包括最常用的操作。有关完整列表，请参阅 [AWS CloudTrail API 参考](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)。

**Topics**
+ [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
+ [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
+ [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
+ [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
+ [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
+ [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
+ [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
+ [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
+ [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
+ [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# `CreateTrail`与 AWS SDK 或 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_CreateTrail_section"></a>

以下代码示例演示如何使用 `CreateTrail`。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
// Routine which creates an AWS CloudTrail trail.
/*!
  \param trailName: The name of the CloudTrail trail.
  \param bucketName: The Amazon S3 bucket designate for publishing logs.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::createTrail(const Aws::String trailName,
                                     const Aws::String bucketName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient trailClient(clientConfig);
    Aws::CloudTrail::Model::CreateTrailRequest request;
    request.SetName(trailName);
    request.SetS3BucketName(bucketName);

    Aws::CloudTrail::Model::CreateTrailOutcome outcome = trailClient.CreateTrail(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created trail " << trailName << std::endl;
    }
    else {
        std::cerr << "Failed to create trail " << trailName <<
                  ": " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[CreateTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/CreateTrail)*中的。

------
#### [ CLI ]

**AWS CLI**  
**创建跟踪**  
以下 `create-trail` 示例创建名为 `Trail1` 的多区域跟踪并指定一个 S3 存储桶。  

```
aws cloudtrail create-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket \
    --is-multi-region-trail
```
输出：  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/create-trail.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：创建将使用存储桶“amzn-s3-demo-bucket”来存储日志文件的跟踪。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**示例 2：创建将使用存储桶“amzn-s3-demo-bucket”来存储日志文件的跟踪。表示日志的 S3 对象的通用键前缀为“mylogs”。当新日志传送到存储桶时，系统将向 SNS 主题“mlog-deliverytopic”发送通知。此示例使用 splatting 向 cmdlet 提供参数值。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CreateTrail](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：创建将使用存储桶“amzn-s3-demo-bucket”来存储日志文件的跟踪。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**示例 2：创建将使用存储桶“amzn-s3-demo-bucket”来存储日志文件的跟踪。表示日志的 S3 对象的通用键前缀为“mylogs”。当新日志传送到存储桶时，系统将向 SNS 主题“mlog-deliverytopic”发送通知。此示例使用 splatting 向 cmdlet 提供参数值。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateTrail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'
require 'aws-sdk-s3'
require 'aws-sdk-sts'

def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, bucket_name)
  resp = sts_client.get_caller_identity({})
  account_id = resp.account

  # Attach policy to an Amazon Simple Storage Service (S3) bucket.
  s3_client.create_bucket(bucket: bucket_name)
  begin
    policy = {
      'Version' => '2012-10-17',
      'Statement' => [
        {
          'Sid' => 'AWSCloudTrailAclCheck20150319',
          'Effect' => 'Allow',
          'Principal' => {
            'Service' => 'cloudtrail.amazonaws.com'
          },
          'Action' => 's3:GetBucketAcl',
          'Resource' => "arn:aws:s3:::#{bucket_name}"
        },
        {
          'Sid' => 'AWSCloudTrailWrite20150319',
          'Effect' => 'Allow',
          'Principal' => {
            'Service' => 'cloudtrail.amazonaws.com'
          },
          'Action' => 's3:PutObject',
          'Resource' => "arn:aws:s3:::#{bucket_name}/AWSLogs/#{account_id}/*",
          'Condition' => {
            'StringEquals' => {
              's3:x-amz-acl' => 'bucket-owner-full-control'
            }
          }
        }
      ]
    }.to_json

    s3_client.put_bucket_policy(
      bucket: bucket_name,
      policy: policy
    )
    puts "Successfully added policy to bucket #{bucket_name}"
  end

  begin
    cloudtrail_client.create_trail({
                                     name: trail_name, # required
                                     s3_bucket_name: bucket_name # required
                                   })

    puts "Successfully created trail: #{trail_name}."
  rescue StandardError => e
    puts "Got error trying to create trail #{trail_name}:\n #{e}"
    puts e
    exit 1
  end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[CreateTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/CreateTrail)*中的。

------

# `DeleteTrail`与 AWS SDK 或 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_DeleteTrail_section"></a>

以下代码示例演示如何使用 `DeleteTrail`。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
// Routine which deletes an AWS CloudTrail trail.
/*!
  \param trailName: The name of the CloudTrail trail.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::deleteTrail(const Aws::String trailName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient trailClient(clientConfig);

    Aws::CloudTrail::Model::DeleteTrailRequest request;
    request.SetName(trailName);

    auto outcome = trailClient.DeleteTrail(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted trail " << trailName << std::endl;
    }
    else {
        std::cerr << "Error deleting trail " << trailName << " " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DeleteTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DeleteTrail)*中的。

------
#### [ CLI ]

**AWS CLI**  
**删除跟踪**  
以下 `delete-trail` 命令删除名为 `Trail1` 的跟踪：  

```
aws cloudtrail delete-trail --name Trail1
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/delete-trail.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：删除指定的跟踪。在运行此命令之前，系统会提示您进行确认。要禁止确认，请添加 -Force 开关参数。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteTrail](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的跟踪。在运行此命令之前，系统会提示您进行确认。要禁止确认，请添加 -Force 开关参数。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteTrail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
  client.delete_trail({
                        name: trail_name # required
                      })
  puts "Successfully deleted trail: #{trail_name}"
rescue StandardError => e
  puts "Got error trying to delete trail: #{trail_name}:"
  puts e
  exit 1
end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[DeleteTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/DeleteTrail)*中的。

------

# 与 AWS SDK `DescribeTrail` 配合使用
<a name="cloudtrail_example_cloudtrail_DescribeTrail_section"></a>

以下代码示例演示了如何使用 `DescribeTrail`。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
// Routine which describes the AWS CloudTrail trails in an account.
/*!
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/

bool AwsDoc::CloudTrail::describeTrails(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient cloudTrailClient(clientConfig);
    Aws::CloudTrail::Model::DescribeTrailsRequest request;

    auto outcome = cloudTrailClient.DescribeTrails(request);
    if (outcome.IsSuccess()) {
        const Aws::Vector<Aws::CloudTrail::Model::Trail> &trails = outcome.GetResult().GetTrailList();
        std::cout << trails.size() << " trail(s) found." << std::endl;
        for (const Aws::CloudTrail::Model::Trail &trail: trails) {
            std::cout << trail.GetName() << std::endl;
        }
    }
    else {
        std::cerr << "Failed to describe trails." << outcome.GetError().GetMessage()
                  << std::endl;
    }
    return outcome.IsSuccess();
}
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DescribeTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DescribeTrail)*中的。

------

# 将 `DescribeTrails` 与 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_DescribeTrails_section"></a>

以下代码示例演示如何使用 `DescribeTrails`。

------
#### [ CLI ]

**AWS CLI**  
**描述跟踪**  
以下 `describe-trails` 示例返回 `Trail1` 和 `Trail2` 的设置。  

```
aws cloudtrail describe-trails \
    --trail-name-list Trail1 Trail2
```
输出：  

```
{
    "trailList": [
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail1",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket",
            "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role",
            "CloudWatchLogsLogGroupArn": "arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail:*",
            "SnsTopicName": "my-topic",
            "HomeRegion": "us-east-1"
        },
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail2",
            "S3KeyPrefix": "my-prefix",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket2",
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/4c5ae5ac-3c13-421e-8335-c7868ef6a769",
            "HomeRegion": "us-east-1"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeTrails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/describe-trails.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回与您账户的当前区域关联的所有跟踪的设置。**  

```
Get-CTTrail
```
**示例 2：返回指定跟踪的设置。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**示例 3：返回在当前 Shell 默认区域以外的区域 [在本例中为法兰克福（eu-central-1）区域] 中创建的指定跟踪的设置。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeTrails](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与您账户的当前区域关联的所有跟踪的设置。**  

```
Get-CTTrail
```
**示例 2：返回指定跟踪的设置。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**示例 3：返回在当前 Shell 默认区域以外的区域 [在本例中为法兰克福（eu-central-1）区域] 中创建的指定跟踪的设置。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTrails](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# 将 `GetTrailStatus` 与 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_GetTrailStatus_section"></a>

以下代码示例演示如何使用 `GetTrailStatus`。

------
#### [ CLI ]

**AWS CLI**  
**获取跟踪的状态**  
以下 `get-trail-status` 命令返回 `Trail1` 的交付和日志记录的详细信息：  

```
aws cloudtrail get-trail-status --name Trail1
```
输出：  

```
{
  "LatestNotificationTime": 1454022144.869,
  "LatestNotificationAttemptSucceeded": "2016-01-28T23:02:24Z",
  "LatestDeliveryAttemptTime": "2016-01-28T23:02:24Z",
  "LatestDeliveryTime": 1454022144.869,
  "TimeLoggingStarted": "2015-11-06T18:36:38Z",
  "LatestDeliveryAttemptSucceeded": "2016-01-28T23:02:24Z",
  "IsLogging": true,
  "LatestCloudWatchLogsDeliveryTime": 1454022144.918,
  "StartLoggingTime": 1446834998.695,
  "StopLoggingTime": 1446834996.933,
  "LatestNotificationAttemptTime": "2016-01-28T23:02:24Z",
  "TimeLoggingStopped": "2015-11-06T18:36:36Z"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[GetTrailStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/get-trail-status.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回名为 “myExampleTrail” 的跟踪的状态信息。返回的数据包括有关传输错误、Amazon SNS 和 Amazon S3 错误以及跟踪的开始和停止日志记录时间的信息。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**示例 2：返回在当前 Shell 默认区域以外的区域 [在本例中为法兰克福（eu-central-1）区域] 中创建的跟踪的状态信息。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [GetTrailStatus](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回名为 “myExampleTrail” 的跟踪的状态信息。返回的数据包括有关传输错误、Amazon SNS 和 Amazon S3 错误以及跟踪的开始和停止日志记录时间的信息。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**示例 2：返回在当前 Shell 默认区域以外的区域 [在本例中为法兰克福（eu-central-1）区域] 中创建的跟踪的状态信息。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [GetTrailStatus](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# 与 AWS SDK `ListTrails` 配合使用
<a name="cloudtrail_example_cloudtrail_ListTrails_section"></a>

以下代码示例演示了如何使用 `ListTrails`。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'

def describe_trails_example(client)
  resp = client.describe_trails({})
  puts "Found #{resp.trail_list.count} trail(s)."

  resp.trail_list.each do |trail|
    puts "Name:           #{trail.name}"
    puts "S3 bucket name: #{trail.s3_bucket_name}"
    puts
  end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[ListTrails](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/ListTrails)*中的。

------

# `LookupEvents`与 AWS SDK 或 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_LookupEvents_section"></a>

以下代码示例演示如何使用 `LookupEvents`。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
// Routine which looks up events captured by AWS CloudTrail.
/*!
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::lookupEvents(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient cloudtrail(clientConfig);

    Aws::String nextToken; // Used for pagination.
    Aws::Vector<Aws::CloudTrail::Model::Event> allEvents;

    Aws::CloudTrail::Model::LookupEventsRequest request;

    size_t count = 0;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::CloudTrail::Model::LookupEventsOutcome outcome = cloudtrail.LookupEvents(
                request);
        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::CloudTrail::Model::Event> &events = outcome.GetResult().GetEvents();
            count += events.size();
            allEvents.insert(allEvents.end(), events.begin(), events.end());
            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cerr << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } while (!nextToken.empty() && count <= 50); // Limit to 50 events.

    std::cout << "Found " << allEvents.size() << " event(s)." << std::endl;

    for (auto &event: allEvents) {
        std::cout << "Event name: " << event.GetEventName() << std::endl;
        std::cout << "Event source: " << event.GetEventSource() << std::endl;
        std::cout << "Event id: " << event.GetEventId() << std::endl;
        std::cout << "Resources: " << std::endl;
        for (auto &resource: event.GetResources()) {
            std::cout << "  " << resource.GetResourceName() << std::endl;
        }
    }

    return true;
}
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[LookupEvents](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/LookupEvents)*中的。

------
#### [ CLI ]

**AWS CLI**  
**查找跟踪的事件**  
以下 `lookup-events` 命令按属性 `EventName` 查找 API 活动事件：  

```
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin
```
输出：  

```
{
  "Events": [
     {
         "EventId": "654ccbc0-ba0d-486a-9076-dbf7274677a7",
         "Username": "my-session-name",
         "EventTime": "2021-11-18T09:41:02-08:00",
         "CloudTrailEvent": "{\"eventVersion\":\"1.02\",\"userIdentity\":{\"type\":\"AssumedRole\",\"principalId\":\"AROAJIKPFTA72SWU4L7T4:my-session-name\",\"arn\":\"arn:aws:sts::123456789012:assumed-role/my-role/my-session-name\",\"accountId\":\"123456789012\",\"sessionContext\":{\"attributes\":{\"mfaAuthenticated\":\"false\",\"creationDate\":\"2016-01-26T21:42:12Z\"},\"sessionIssuer\":{\"type\":\"Role\",\"principalId\":\"AROAJIKPFTA72SWU4L7T4\",\"arn\":\"arn:aws:iam::123456789012:role/my-role\",\"accountId\":\"123456789012\",\"userName\":\"my-role\"}}},\"eventTime\":\"2016-01-26T21:42:12Z\",\"eventSource\":\"signin.amazonaws.com\",\"eventName\":\"ConsoleLogin\",\"awsRegion\":\"us-east-1\",\"sourceIPAddress\":\"72.21.198.70\",\"userAgent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36\",\"requestParameters\":null,\"responseElements\":{\"ConsoleLogin\":\"Success\"},\"additionalEventData\":{\"MobileVersion\":\"No\",\"MFAUsed\":\"No\"},\"eventID\":\"654ccbc0-ba0d-486a-9076-dbf7274677a7\",\"eventType\":\"AwsConsoleSignIn\",\"recipientAccountId\":\"123456789012\"}",
         "EventName": "ConsoleLogin",
         "Resources": []
     }
  ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[LookupEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/lookup-events.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回过去七天内发生的所有事件。默认情况下，cmdlet 会自动发出多个调用以传送所有事件，当服务指示没有更多数据可用时退出。**  

```
Find-CTEvent
```
**示例 2：返回过去七天内发生的所有事件，且指定的区域不是当前 Shell 默认区域。**  

```
Find-CTEvent -Region eu-central-1
```
**示例 3：返回与 RunInstances API 调用关联的所有事件。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**示例 4：返回前 5 个可用事件。**  

```
Find-CTEvent -MaxResult 5
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [LookupEvents](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回过去七天内发生的所有事件。默认情况下，cmdlet 会自动发出多个调用以传送所有事件，当服务指示没有更多数据可用时退出。**  

```
Find-CTEvent
```
**示例 2：返回过去七天内发生的所有事件，且指定的区域不是当前 Shell 默认区域。**  

```
Find-CTEvent -Region eu-central-1
```
**示例 3：返回与 RunInstances API 调用关联的所有事件。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**示例 4：返回前 5 个可用事件。**  

```
Find-CTEvent -MaxResult 5
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [LookupEvents](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)中查找完整示例，了解如何进行设置和运行。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'

# @param [Object] client
def lookup_events_example(client)
  resp = client.lookup_events
  puts "Found #{resp.events.count} events:"
  resp.events.each do |e|
    puts "Event name:   #{e.event_name}"
    puts "Event ID:     #{e.event_id}"
    puts "Event time:   #{e.event_time}"
    puts 'Resources:'

    e.resources.each do |r|
      puts "  Name:       #{r.resource_name}"
      puts "  Type:       #{r.resource_type}"
      puts ''
    end
  end
end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[LookupEvents](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/LookupEvents)*中的。

------

# 将 `StartLogging` 与 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_StartLogging_section"></a>

以下代码示例演示如何使用 `StartLogging`。

------
#### [ CLI ]

**AWS CLI**  
**为跟踪启动日志记录**  
以下 `start-logging` 命令为 `Trail1` 开启日志记录：  

```
aws cloudtrail start-logging --name Trail1
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[StartLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/start-logging.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：开始为名为 “myExampleTrail” 的跟踪记录 AWS API 调用和日志文件传输。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Start-CTLogging -Name myExampleTrail
```
**示例 2：开始记录在当前外壳默认区域（在本例中为法兰克福 (eu-central-1) 区域）中创建的跟踪 AWS API 调用和日志文件传输。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [StartLogging](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：开始为名为 “myExampleTrail” 的跟踪记录 AWS API 调用和日志文件传输。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Start-CTLogging -Name myExampleTrail
```
**示例 2：开始记录在当前外壳默认区域（在本例中为法兰克福 (eu-central-1) 区域）中创建的跟踪 AWS API 调用和日志文件传输。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StartLogging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# 将 `StopLogging` 与 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_StopLogging_section"></a>

以下代码示例演示如何使用 `StopLogging`。

------
#### [ CLI ]

**AWS CLI**  
**停止跟踪的日志记录**  
以下 `stop-logging` 命令为 `Trail1` 关闭日志记录：  

```
aws cloudtrail stop-logging --name Trail1
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[StopLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/stop-logging.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：暂停记录名为 “myExampleTrail” 的跟踪的 AWS API 调用和日志文件传输。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Stop-CTLogging -Name myExampleTrail
```
**示例 2：暂停记录在当前外壳默认区域（在本例中为法兰克福（eu-central-1）区域）中创建的跟踪 AWS API 调用和日志文件传输。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [StopLogging](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：暂停记录名为 “myExampleTrail” 的跟踪的 AWS API 调用和日志文件传输。此示例假设跟踪是在与当前 Shell 默认区域相同的区域中创建的。**  

```
Stop-CTLogging -Name myExampleTrail
```
**示例 2：暂停记录在当前外壳默认区域（在本例中为法兰克福（eu-central-1）区域）中创建的跟踪 AWS API 调用和日志文件传输。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [StopLogging](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# 将 `UpdateTrail` 与 CLI 配合使用
<a name="cloudtrail_example_cloudtrail_UpdateTrail_section"></a>

以下代码示例演示如何使用 `UpdateTrail`。

------
#### [ CLI ]

**AWS CLI**  
**更新跟踪**  
以下 `update-trail` 示例更新跟踪以使用现有存储桶进行日志传输。  

```
aws cloudtrail update-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket
```
输出：  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[UpdateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-trail.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：更新指定的跟踪，以便记录全局服务事件（例如来自 IAM 的服务事件），并将后续日志文件的通用键前缀更改为“globallogs”。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**示例 2：更新指定的跟踪，以便将有关新日志传输的通知发送到指定的 SNS 主题。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**示例 3：更新指定的跟踪，以便将日志传送到其它存储桶。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [UpdateTrail](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：更新指定的跟踪，以便记录全局服务事件（例如来自 IAM 的服务事件），并将后续日志文件的通用键前缀更改为“globallogs”。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**示例 2：更新指定的跟踪，以便将有关新日志传输的通知发送到指定的 SNS 主题。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**示例 3：更新指定的跟踪，以便将日志传送到其它存储桶。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------