CloudTrail 使用範例 AWS CLI - AWS Command Line Interface

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

CloudTrail 使用範例 AWS CLI

下列程式碼範例說明如何使用 AWS Command Line Interface 與來執行動作及實作常見案例 CloudTrail。

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

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

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

主題

動作

下列程式碼範例會示範如何使用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" }

下列程式碼範例會示範如何使用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 儲存貯體的 S3 PutObject 和 DeleteObject API 呼叫、記錄名為 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 錄事件。

下列程式碼範例會示範如何使用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中的。