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

使用 Amazon 开发工具包列出用户的 IAM 访问密钥

以下代码示例显示如何列出用户的 IAM 访问密钥。

C++
SDK for C++
注意

GitHub 上还有更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

bool AwsDoc::IAM::listAccessKeys(const Aws::String &userName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::ListAccessKeysRequest request; request.SetUserName(userName); bool done = false; bool header = false; while (!done) { auto outcome = iam.ListAccessKeys(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to list access keys for user " << userName << ": " << outcome.GetError().GetMessage() << std::endl; return false; } if (!header) { std::cout << std::left << std::setw(32) << "UserName" << std::setw(30) << "KeyID" << std::setw(20) << "Status" << std::setw(20) << "CreateDate" << std::endl; header = true; } const auto &keys = outcome.GetResult().GetAccessKeyMetadata(); const Aws::String DATE_FORMAT = "%Y-%m-%d"; for (const auto &key: keys) { Aws::String statusString = Aws::IAM::Model::StatusTypeMapper::GetNameForStatusType( key.GetStatus()); std::cout << std::left << std::setw(32) << key.GetUserName() << std::setw(30) << key.GetAccessKeyId() << std::setw(20) << statusString << std::setw(20) << key.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) << std::endl; } if (outcome.GetResult().GetIsTruncated()) { request.SetMarker(outcome.GetResult().GetMarker()); } else { done = true; } } return true; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 ListAccessKeys

Go
SDK for Go V2
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/iam" ) // IAMListAccessKeysAPI defines the interface for the ListAccessKeys function. // We use this interface to test the function using a mocked service. type IAMListAccessKeysAPI interface { ListAccessKeys(ctx context.Context, params *iam.ListAccessKeysInput, optFns ...func(*iam.Options)) (*iam.ListAccessKeysOutput, error) } // GetAccessKeys retrieves up to the AWS Identity and Access Management (IAM) access keys for a user. // 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 ListAccessKeysOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to ListAccessKeys. func GetAccessKeys(c context.Context, api IAMListAccessKeysAPI, input *iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) { return api.ListAccessKeys(c, input) } func main() { maxItems := flag.Int("m", 10, "The maximum number of access keys to show") userName := flag.String("u", "", "The name of the user") flag.Parse() if *userName == "" { fmt.Println("You must supply the name of a user (-u USER)") return } if *maxItems < 0 { *maxItems = 10 } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := iam.NewFromConfig(cfg) input := &iam.ListAccessKeysInput{ MaxItems: aws.Int32(int32(*maxItems)), UserName: userName, } result, err := GetAccessKeys(context.TODO(), client, input) if err != nil { fmt.Println("Got an error retrieving user access keys:") fmt.Println(err) return } for _, key := range result.AccessKeyMetadata { fmt.Println("Status for access key " + *key.AccessKeyId + ": " + string(key.Status)) } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 ListAccessKeys

Java
SDK for Java 2.x
注意

GitHub 上还有更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public static void listKeys( IamClient iam,String userName ){ try { boolean done = false; String newMarker = null; while (!done) { ListAccessKeysResponse response; if(newMarker == null) { ListAccessKeysRequest request = ListAccessKeysRequest.builder() .userName(userName) .build(); response = iam.listAccessKeys(request); } else { ListAccessKeysRequest request = ListAccessKeysRequest.builder() .userName(userName) .marker(newMarker) .build(); response = iam.listAccessKeys(request); } for (AccessKeyMetadata metadata : response.accessKeyMetadata()) { System.out.format("Retrieved access key %s", metadata.accessKeyId()); } if (!response.isTruncated()) { done = true; } else { newMarker = response.marker(); } } } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 ListAccessKeys

JavaScript
SDK for JavaScript V3
注意

GitHub 上还有更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建客户端。

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 { ListAccessKeysCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { MaxItems: 5, UserName: "IAM_USER_NAME", //IAM_USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new ListAccessKeysCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
SDK for JavaScript V2
注意

GitHub 上还有更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// 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'}); var params = { MaxItems: 5, UserName: 'IAM_USER_NAME' }; iam.listAccessKeys(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

注意

GitHub 上还有更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun listKeys(userNameVal: String?) { val request = ListAccessKeysRequest { userName = userNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAccessKeys(request) response.accessKeyMetadata?.forEach { md -> println("Retrieved access key ${md.accessKeyId}") } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 ListAccessKeys

Python
适用于 Python (Boto3) 的 SDK
注意

GitHub 上还有更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

def list_keys(user_name): """ Lists the keys owned by the specified user. :param user_name: The name of the user. :return: The list of keys owned by the user. """ try: keys = list(iam.User(user_name).access_keys.all()) logger.info("Got %s access keys for %s.", len(keys), user_name) except ClientError: logger.exception("Couldn't get access keys for %s.", user_name) raise else: return keys
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 ListAccessKeys

Ruby
SDK for Ruby
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

# Deletes a user. If the user has inline policies or access keys, they are deleted # before the user is deleted. # # @param user [Aws::IAM::User] The user to delete. def delete_user(user) user.policies.each do |policy| name = policy.name policy.delete puts("Deleted user policy #{name}.") end user.access_keys.each do |key| key.delete puts("Deleted access key for user #{user.name}.") end name = user.name user.delete puts("Deleted user #{name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't detach policies and delete user #{user.name}. Here's why:") puts("\t#{e.code}: #{e.message}") end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 ListAccessKeys

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