使用 Amazon 开发工具包列出 IAM 用户
以下代码示例显示如何列出 IAM 用户。
警告
为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 Amazon IAM Identity Center (successor to Amazon Single Sign-On)。
- .NET
-
- Amazon SDK for .NET
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 /// <summary> /// List IAM users. /// </summary> /// <returns>A list of IAM users.</returns> public async Task<List<User>> ListUsersAsync() { var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest()); var users = new List<User>(); await foreach (var response in listUsersPaginator.Responses) { users.AddRange(response.Users); } return users; }-
有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 ListUsers。
-
- C++
-
- SDK for C++
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 bool AwsDoc::IAM::listUsers(const Aws::Client::ClientConfiguration &clientConfig) { const Aws::String DATE_FORMAT = "%Y-%m-%d"; Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::ListUsersRequest request; bool done = false; bool header = false; while (!done) { auto outcome = iam.ListUsers(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to list iam users:" << outcome.GetError().GetMessage() << std::endl; return false; } if (!header) { std::cout << std::left << std::setw(32) << "Name" << std::setw(30) << "ID" << std::setw(64) << "Arn" << std::setw(20) << "CreateDate" << std::endl; header = true; } const auto &users = outcome.GetResult().GetUsers(); for (const auto &user: users) { std::cout << std::left << std::setw(32) << user.GetUserName() << std::setw(30) << user.GetUserId() << std::setw(64) << user.GetArn() << std::setw(20) << user.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 参考》中的 ListUsers。
-
- Go
-
- SDK for Go V2
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 // UserWrapper encapsulates user actions used in the examples. // It contains an IAM service client that is used to perform user actions. type UserWrapper struct { IamClient *iam.Client } // ListUsers gets up to maxUsers number of users. func (wrapper UserWrapper) ListUsers(maxUsers int32) ([]types.User, error) { var users []types.User result, err := wrapper.IamClient.ListUsers(context.TODO(), &iam.ListUsersInput{ MaxItems: aws.Int32(maxUsers), }) if err != nil { log.Printf("Couldn't list users. Here's why: %v\n", err) } else { users = result.Users } return users, err }-
有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 ListUsers
。
-
- Java
-
- SDK for Java 2.x
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 public static void listAllUsers(IamClient iam ) { try { boolean done = false; String newMarker = null; while(!done) { ListUsersResponse response; if (newMarker == null) { ListUsersRequest request = ListUsersRequest.builder().build(); response = iam.listUsers(request); } else { ListUsersRequest request = ListUsersRequest.builder() .marker(newMarker) .build(); response = iam.listUsers(request); } for(User user : response.users()) { System.out.format("\n Retrieved user %s", user.userName()); AttachedPermissionsBoundary permissionsBoundary = user.permissionsBoundary(); if (permissionsBoundary != null) System.out.format("\n Permissions boundary details %s", permissionsBoundary.permissionsBoundaryTypeAsString()); } 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 参考》中的 ListUsers。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 列出用户。
import { ListUsersCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); export const listUsers = async () => { const command = new ListUsersCommand({ MaxItems: 10 }); const response = await client.send(command); response.Users?.forEach(({ UserName, CreateDate }) => { console.log(`${UserName} created on: ${CreateDate}`); }); return response; };-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 ListUsers。
-
- 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: 10 }; iam.listUsers(params, function(err, data) { if (err) { console.log("Error", err); } else { var users = data.Users || []; users.forEach(function(user) { console.log("User " + user.UserName + " created", user.CreateDate); }); } });-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 ListUsers。
-
- Kotlin
-
- SDK for Kotlin
-
注意
这是适用于预览版中功能的预发行文档。本文档随时可能更改。
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 suspend fun listAllUsers() { IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listUsers(ListUsersRequest { }) response.users?.forEach { user -> println("Retrieved user ${user.userName}") val permissionsBoundary = user.permissionsBoundary if (permissionsBoundary != null) println("Permissions boundary details ${permissionsBoundary.permissionsBoundaryType}") } } }-
有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 ListUsers
。
-
- PHP
-
- SDK for PHP
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 $uuid = uniqid(); $service = new IAMService(); public function listUsers($pathPrefix = "", $marker = "", $maxItems = 0) { $listUsersArguments = []; if ($pathPrefix) { $listUsersArguments["PathPrefix"] = $pathPrefix; } if ($marker) { $listUsersArguments["Marker"] = $marker; } if ($maxItems) { $listUsersArguments["MaxItems"] = $maxItems; } return $this->iamClient->listUsers($listUsersArguments); }-
有关 API 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 ListUsers。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
注意
在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 def list_users(): """ Lists the users in the current account. :return: The list of users. """ try: users = list(iam.users.all()) logger.info("Got %s users.", len(users)) except ClientError: logger.exception("Couldn't get users.") raise else: return users-
有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 ListUsers。
-
- Ruby
-
- SDK for Ruby
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 # Lists up to a specified number of users in the account. # # @param count [Integer] The maximum number of users to list. def list_users(count) @iam_resource.users.limit(count).each do |user| puts("\t#{user.name}") end rescue Aws::Errors::ServiceError => e puts("Couldn't list users for the account. Here's why:") puts("\t#{e.code}: #{e.message}") raise end-
有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 ListUsers。
-
- Rust
-
- SDK for Rust
-
注意
本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 pub async fn list_users( client: &iamClient, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListUsersOutput, SdkError<ListUsersError>> { let response = client .list_users() .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }-
有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 ListUsers
。
-
- Swift
-
- SDK for Swift
-
注意
这是预览版 SDK 的预发布文档。本文档随时可能更改。
注意
在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 public func listUsers() async throws -> [MyUserRecord] { var userList: [MyUserRecord] = [] var marker: String? = nil var isTruncated: Bool repeat { let input = ListUsersInput(marker: marker) let output = try await client.listUsers(input: input) guard let users = output.users else { return userList } for user in users { if let id = user.userId, let name = user.userName { userList.append(MyUserRecord(id: id, name: name)) } } marker = output.marker isTruncated = output.isTruncated } while isTruncated == true return userList }-
有关 API 详细信息,请参阅 Amazon SDK for Swift API 参考中的 ListUsers
。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。