使用 Amazon 开发工具包获取有关上次使用 IAM 访问密钥的数据 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包获取有关上次使用 IAM 访问密钥的数据

以下代码示例显示如何获取关于上次使用 IAM 访问密钥的数据。

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/iam" ) // IAMGetAccessKeyLastUsedAPI defines the interface for the GetAccessKeyLastUsed function. // We use this interface to test the function using a mocked service. type IAMGetAccessKeyLastUsedAPI interface { GetAccessKeyLastUsed(ctx context.Context, params *iam.GetAccessKeyLastUsedInput, optFns ...func(*iam.Options)) (*iam.GetAccessKeyLastUsedOutput, error) } // WhenWasKeyUsed retrieves when an AWS Identity and Access Management (IAM) access key was last used, including the AWS Region and with which service. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If successful, a GetAccessKeyLastUsedOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to GetAccessKeyLastUsed. func WhenWasKeyUsed(c context.Context, api IAMGetAccessKeyLastUsedAPI, input *iam.GetAccessKeyLastUsedInput) (*iam.GetAccessKeyLastUsedOutput, error) { return api.GetAccessKeyLastUsed(c, input) } func main() { keyID := flag.String("k", "", "The ID of the access key") flag.Parse() if *keyID == "" { fmt.Println("You must supply the ID of an access key (-k KEY-ID)") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := iam.NewFromConfig(cfg) input := &iam.GetAccessKeyLastUsedInput{ AccessKeyId: keyID, } result, err := WhenWasKeyUsed(context.TODO(), client, input) if err != nil { fmt.Println("Got an error retrieving when access key was last used:") fmt.Println(err) return } fmt.Println("The key was last used:", *result.AccessKeyLastUsed) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 GetAccessKeyLastUsed

JavaScript
SDK for JavaScript V3
提示

要了解如何设置和运行此示例,请参阅 GitHub

创建客户端。

import { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

获取访问密钥。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetAccessKeyLastUsedCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccessKeyId: "ACCESS_KEY_ID" }; //ACCESS_KEY_ID export const run = async () => { try { const data = await iamClient.send(new GetAccessKeyLastUsedCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
SDK for JavaScript V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the IAM service object var iam = new AWS.IAM({apiVersion: '2010-05-08'}); iam.getAccessKeyLastUsed({AccessKeyId: 'ACCESS_KEY_ID'}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.AccessKeyLastUsed); } });
Python
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

def get_last_use(key_id): """ Gets information about when and how a key was last used. :param key_id: The ID of the key to look up. :return: Information about the key's last use. """ try: response = iam.meta.client.get_access_key_last_used(AccessKeyId=key_id) last_used_date = response['AccessKeyLastUsed'].get('LastUsedDate', None) last_service = response['AccessKeyLastUsed'].get('ServiceName', None) logger.info( "Key %s was last used by %s on %s to access %s.", key_id, response['UserName'], last_used_date, last_service) except ClientError: logger.exception("Couldn't get last use of key %s.", key_id) raise else: return response
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 GetAccessKeyLastUsed

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。