使用 的 CloudTrail 範例 AWS CLI - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 的 CloudTrail 範例 AWS CLI

下列程式碼範例示範如何使用 AWS Command Line Interface with CloudTrail 來執行動作和實作常見案例。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在相關案例中查看內容中的動作。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

主題

動作

下列程式碼範例示範如何使用 add-tags

AWS CLI

將標籤新增至追蹤

下列add-tags命令會新增 的標籤Trail1

aws cloudtrail add-tags --resource-id arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 --tags-list Key=name,Value=Alice Key=location,Value=us
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 AddTags

下列程式碼範例示範如何使用 create-subscription

AWS CLI

建立和設定追蹤 AWS 的資源

下列create-subscription命令會為 建立新的 S3 儲存貯體和 SNS 主題Trail1

aws cloudtrail create-subscription --name Trail1 --s3-new-bucket my-bucket --sns-new-topic my-topic

輸出:

Setting up new S3 bucket my-bucket... Setting up new SNS topic my-topic... Creating/updating CloudTrail configuration... CloudTrail configuration: { "trailList": [ { "IncludeGlobalServiceEvents": true, "Name": "Trail1", "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1", "LogFileValidationEnabled": false, "IsMultiRegionTrail": false, "S3BucketName": "my-bucket", "SnsTopicName": "my-topic", "HomeRegion": "us-east-1" } ], "ResponseMetadata": { "HTTPStatusCode": 200, "RequestId": "f39e51f6-c615-11e5-85bd-d35ca21ee3e2" } } Starting CloudTrail service... Logs will be delivered to my-bucket

下列程式碼範例示範如何使用 create-trail

AWS CLI

若要建立追蹤

下列create-trail命令會建立名為 的多區域追蹤,Trail1並指定 S3 儲存貯體:

aws cloudtrail create-trail --name Trail1 --s3-bucket-name my-bucket --is-multi-region-trail

輸出:

{ "IncludeGlobalServiceEvents": true, "Name": "Trail1", "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1", "LogFileValidationEnabled": false, "IsMultiRegionTrail": true, "S3BucketName": "my-bucket" }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 CreateTrail

下列程式碼範例示範如何使用 delete-trail

AWS CLI

若要刪除追蹤

下列delete-trail命令會刪除名為 的追蹤Trail1

aws cloudtrail delete-trail --name Trail1
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 DeleteTrail

下列程式碼範例示範如何使用 describe-trails

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": "my-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": "my-bucket", "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/4c5ae5ac-3c13-421e-8335-c7868ef6a769", "HomeRegion": "us-east-1" } ] }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 DescribeTrails

下列程式碼範例示範如何使用 get-event-selectors

AWS CLI

檢視追蹤的事件選取器設定

下列get-event-selectors命令會傳回 的設定Trail1

aws cloudtrail get-event-selectors --trail-name Trail1

輸出:

{ "EventSelectors": [ { "IncludeManagementEvents": true, "DataResources": [], "ReadWriteType": "All" } ], "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1" }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 GetEventSelectors

下列程式碼範例示範如何使用 get-trail-status

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

下列程式碼範例示範如何使用 list-public-keys

AWS CLI

列出追蹤的所有公有金鑰

下列list-public-keys命令會傳回所有公有金鑰,其私有金鑰用於在指定時間範圍內簽署摘要檔案:

aws cloudtrail list-public-keys --start-time 2016-01-01T20:30:00.000Z

輸出:

{ "PublicKeyList": [ { "ValidityStartTime": 1453076702.0, "ValidityEndTime": 1455668702.0, "Value": "MIIBCgKCAQEAlSS3cl92HDycr/MTj0moOhas8habjrraXw+KzlWF0axSI2tcF+3iJ9BKQAVSKxGwxwu3m0wG3J+kUl1xboEcEPHYoIYMbgfSw7KGnuDKwkLzsQWhUJ0cIbOHASox1vv/5fNXkrHhGbDCHeVXm804c83nvHUEFYThr1PfyP/8HwrCtR3FX5OANtQCP61C1nJtSSkC8JSQUOrIP4CuwJjc+4WGDk+BGH5m9iuiAKkipEHWmUl8/P7XpfpWQuk4h8g3pXZOrNXr08lbh4d39svj7UqdhvOXoBISp9t/EXYuePGEtBdrKD9Dz+VHwyUPtBQvYr9BnkF88qBnaPNhS44rzwIDAQAB", "Fingerprint": "7f3f401420072e50a65a141430817ab3" } ] }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 ListPublicKeys

下列程式碼範例示範如何使用 list-tags

AWS CLI

列出追蹤的標籤

下列list-tags命令會列出 Trail1和 的標籤Trail2

aws cloudtrail list-tags --resource-id-list arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2

輸出:

{ "ResourceTagList": [ { "ResourceId": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1", "TagsList": [ { "Value": "Alice", "Key": "name" }, { "Value": "us", "Key": "location" } ] }, { "ResourceId": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2", "TagsList": [ { "Value": "Bob", "Key": "name" } ] } ] }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 ListTags

下列程式碼範例示範如何使用 lookup-events

AWS CLI

若要查詢追蹤的事件

下列lookup-events命令會依 屬性 查詢 API 活動事件EventName

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

下列程式碼範例示範如何使用 put-event-selectors

AWS CLI

範例 1:使用進階事件選取器設定追蹤以記錄管理事件和資料事件

您可以為進階事件選取器新增進階事件選取器和條件,追蹤上所有條件和選取器的值上限為 500 個。您可以使用進階事件選取器來記錄所有可用的資料事件類型。您可以使用進階事件選取器或基本事件選取器,但不能同時使用兩者。如果您將進階事件選取器套用至追蹤,則會覆寫任何現有的基本事件選取器。

下列範例會為名為 的追蹤建立進階事件選取器,myTrail以記錄所有管理事件、記錄除一個 S3 儲存貯體以外的所有 S3 PutObject 和 DeleteObject API Word呼叫、記錄名為 的 Lambda 函數的資料 API 呼叫myFunction,以及記錄名為 的 SNS 主題上的發佈 API 呼叫myTopic

aws cloudtrail put-event-selectors \ --trail-name myTrail \ --advanced-event-selectors '[{"Name": "Log all management events", "FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Management"] }] },{"Name": "Log PutObject and DeleteObject events for all but one bucket","FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Data"] },{ "Field": "resources.type", "Equals": ["AWS::S3::Object"] },{ "Field": "eventName", "Equals": ["PutObject","DeleteObject"] },{ "Field": "resources.ARN", "NotStartsWith": ["arn:aws:s3:::sample_bucket_name/"] }]},{"Name": "Log data events for a specific Lambda function","FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Data"] },{ "Field": "resources.type", "Equals": ["AWS::Lambda::Function"] },{ "Field": "resources.ARN", "Equals": ["arn:aws:lambda:us-east-1:123456789012:function:myFunction"] }]},{"Name": "Log all Publish API calls on a specific SNS topic","FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Data"] },{ "Field": "resources.type", "Equals": ["AWS::SNS::Topic"] },{ "Field": "eventName", "Equals": ["Publish"] },{ "Field": "resources.ARN", "Equals": ["arn:aws:sns:us-east-1:123456789012:myTopic.fifo"] }]}]'

輸出:

{ "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/myTrail", "AdvancedEventSelectors": [ { "Name": "Log all management events", "FieldSelectors": [ { "Field": "eventCategory", "Equals": [ "Management" ] } ] }, { "Name": "Log PutObject and DeleteObject events for all but one bucket", "FieldSelectors": [ { "Field": "eventCategory", "Equals": [ "Data" ] }, { "Field": "resources.type", "Equals": [ "AWS::S3::Object" ] }, { "Field": "eventName", "Equals": [ "PutObject", "DeleteObject" ] }, { "Field": "resources.ARN", "NotStartsWith": [ "arn:aws:s3:::sample_bucket_name/" ] } ] }, { "Name": "Log data events for a specific Lambda function", "FieldSelectors": [ { "Field": "eventCategory", "Equals": [ "Data" ] }, { "Field": "resources.type", "Equals": [ "AWS::Lambda::Function" ] }, { "Field": "resources.ARN", "Equals": [ "arn:aws:lambda:us-east-1:123456789012:function:myFunction" ] } ] }, { "Name": "Log all Publish API calls on a specific SNS topic", "FieldSelectors": [ { "Field": "eventCategory", "Equals": [ "Data" ] }, { "Field": "resources.type", "Equals": [ "AWS::SNS::Topic" ] }, { "Field": "eventName", "Equals": [ "Publish" ] }, { "Field": "resources.ARN", "Equals": [ "arn:aws:sns:us-east-1:123456789012:myTopic.fifo" ] } ] } ] }

如需詳細資訊,請參閱 AWS CloudTrail 使用者指南中的使用進階事件選取器記錄事件

範例 2:設定追蹤的事件選取器,以記錄所有管理事件和資料事件

一個追蹤最多可以設定 5 個事件選取器和 250 個資料資源。事件選取器也稱為基本事件選取器。您可以使用事件選取器來記錄 S3 物件、Lambda 函數和 DynnamoDB 資料表的管理事件和資料事件。若要記錄其他資源類型的資料事件,您必須使用進階事件選取器。

下列範例會為名為 的追蹤建立事件選取器TrailName,以包含所有管理事件、兩個 Amazon S3 儲存貯體/字首組合的資料事件,以及名為 的單一 AWS Lambda 函數的資料事件hello-world-python-function

aws cloudtrail put-event-selectors \ --trail-name TrailName \ --event-selectors '[{"ReadWriteType": "All","IncludeManagementEvents": true,"DataResources": [{"Type":"AWS::S3::Object", "Values": ["arn:aws:s3:::mybucket/prefix","arn:aws:s3:::mybucket2/prefix2"]},{"Type": "AWS::Lambda::Function","Values": ["arn:aws:lambda:us-west-2:999999999999:function:hello-world-python-function"]}]}]'

輸出:

{ "EventSelectors": [ { "IncludeManagementEvents": true, "DataResources": [ { "Values": [ "arn:aws:s3:::mybucket/prefix", "arn:aws:s3:::mybucket2/prefix2" ], "Type": "AWS::S3::Object" }, { "Values": [ "arn:aws:lambda:us-west-2:123456789012:function:hello-world-python-function" ], "Type": "AWS::Lambda::Function" }, ], "ReadWriteType": "All" } ], "TrailARN": "arn:aws:cloudtrail:us-east-2:123456789012:trail/TrailName" }

如需詳細資訊,請參閱 AWS CloudTrail 使用者指南中的使用基本事件選取器記錄事件

範例 3:設定追蹤的事件選取器,以記錄管理事件、S3 物件上的所有 S3 資料事件,以及帳戶中函數上的所有 Lambda 資料事件

下列範例會為名為 的追蹤建立事件選取器TrailName2,其中包含所有管理事件,以及 AWS 帳戶中所有 Amazon S3 儲存貯體和 AWS Lambda 函數的所有資料事件。

aws cloudtrail put-event-selectors \ --trail-name TrailName2 \ --event-selectors '[{"ReadWriteType": "All","IncludeManagementEvents": true,"DataResources": [{"Type":"AWS::S3::Object", "Values": ["arn:aws:s3"]},{"Type": "AWS::Lambda::Function","Values": ["arn:aws:lambda"]}]}]'

輸出:

{ "EventSelectors": [ { "IncludeManagementEvents": true, "DataResources": [ { "Values": [ "arn:aws:s3" ], "Type": "AWS::S3::Object" }, { "Values": [ "arn:aws:lambda" ], "Type": "AWS::Lambda::Function" }, ], "ReadWriteType": "All" } ], "TrailARN": "arn:aws:cloudtrail:us-east-2:123456789012:trail/TrailName2" }

如需詳細資訊,請參閱 AWS CloudTrail 使用者指南中的使用基本事件選取器記錄事件

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 PutEventSelectors

下列程式碼範例示範如何使用 remove-tags

AWS CLI

若要移除追蹤的標籤

下列remove-tags命令會移除 的指定標籤Trail1

aws cloudtrail remove-tags --resource-id arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 --tags-list Key=name Key=location
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 RemoveTags

下列程式碼範例示範如何使用 start-logging

AWS CLI

開始記錄追蹤

下列start-logging命令會開啟 的記錄Trail1

aws cloudtrail start-logging --name Trail1
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 StartLogging

下列程式碼範例示範如何使用 stop-logging

AWS CLI

停止記錄追蹤

下列stop-logging命令會關閉 的記錄Trail1

aws cloudtrail stop-logging --name Trail1
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 StopLogging

下列程式碼範例示範如何使用 update-subscription

AWS CLI

更新追蹤的組態設定

下列update-subscription命令會更新追蹤,以指定新的 S3 儲存貯體和 SNS 主題:

aws cloudtrail update-subscription --name Trail1 --s3-new-bucket my-bucket-new --sns-new-topic my-topic-new

輸出:

Setting up new S3 bucket my-bucket-new... Setting up new SNS topic my-topic-new... Creating/updating CloudTrail configuration... CloudTrail configuration: { "trailList": [ { "IncludeGlobalServiceEvents": true, "Name": "Trail1", "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1", "LogFileValidationEnabled": false, "IsMultiRegionTrail": false, "S3BucketName": "my-bucket-new", "SnsTopicName": "my-topic-new", "HomeRegion": "us-east-1" } ], "ResponseMetadata": { "HTTPStatusCode": 200, "RequestId": "31126f8a-c616-11e5-9cc6-2fd637936879" } }

下列程式碼範例示範如何使用 update-trail

AWS CLI

更新追蹤

下列update-trail命令會更新追蹤,以使用現有儲存貯體進行日誌交付:

aws cloudtrail update-trail --name Trail1 --s3-bucket-name my-bucket

輸出:

{ "IncludeGlobalServiceEvents": true, "Name": "Trail1", "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1", "LogFileValidationEnabled": false, "IsMultiRegionTrail": true, "S3BucketName": "my-bucket" }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 UpdateTrail

下列程式碼範例示範如何使用 validate-logs

AWS CLI

驗證日誌檔案

下列validate-logs命令會驗證 的日誌Trail1

aws cloudtrail validate-logs --trail-arn arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 --start-time 20160129T19:00:00Z

輸出:

Validating log files for trail arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 between 2016-01-29T19:00:00Z and 2016-01-29T22:15:43Z Results requested for 2016-01-29T19:00:00Z to 2016-01-29T22:15:43Z Results found for 2016-01-29T19:24:57Z to 2016-01-29T21:24:57Z: 3/3 digest files valid 15/15 log files valid
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 ValidateLogs