Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Usare ListUsers con un AWS SDK o CLI
I seguenti esempi di codice mostrano come usare ListUsers.
Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:
- .NET
-
- SDK per .NET
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. /// <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; }-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK per .NET Riferimento API.
-
- Bash
-
- AWS CLI con script Bash
-
Nota
C'è dell'altro GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_list_users # # List the IAM users in the account. # # Returns: # The list of users names # And: # 0 - If the user already exists. # 1 - If the user doesn't exist. ############################################################################### function iam_list_users() { local option OPTARG # Required to use getopts command in a function. local error_code # bashsupport disable=BP5008 function usage() { echo "function iam_list_users" echo "Lists the AWS Identity and Access Management (IAM) user in the account." echo "" } # Retrieve the calling parameters. while getopts "h" option; do case "${option}" in h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 local response response=$(aws iam list-users \ --output text \ --query "Users[].UserName") error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports list-users operation failed.$response" return 1 fi echo "$response" return 0 }-
Per i dettagli sull'API, vedi ListUsers nel AWS CLI Riferimento al comando.
-
- C++
-
- SDK per C++
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. 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; }-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK per C++ Riferimento API.
-
- CLI
-
- AWS CLI
-
Come elencare gli utenti IAM
Quanto segue
list-usersL'esempio elenca gli utenti IAM nell'account corrente.aws iam list-usersOutput:
{ "Users": [ { "UserName": "Adele", "Path": "/", "CreateDate": "2013-03-07T05:14:48Z", "UserId": "AKIAI44QH8DHBEXAMPLE", "Arn": "arn:aws:iam::123456789012:user/Adele" }, { "UserName": "Bob", "Path": "/", "CreateDate": "2012-09-21T23:03:13Z", "UserId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::123456789012:user/Bob" } ] }Per ulteriori informazioni, consulta Elencazione degli utenti IAM nella Guida per l’utente IAM AWS .
-
Per i dettagli sull'API, consulta ListUsers
nel AWS CLI Riferimento al comando.
-
- Go
-
- SDK per Go V2
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. import ( "context" "encoding/json" "errors" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/iam" "github.com/aws/aws-sdk-go-v2/service/iam/types" "github.com/aws/smithy-go" ) // 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(ctx context.Context, maxUsers int32) ([]types.User, error) { var users []types.User result, err := wrapper.IamClient.ListUsers(ctx, &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 }-
Per i dettagli sull'API, vedi ListUsers
nel AWS SDK per Go Riferimento API.
-
- Java
-
- SDK per Java 2.x
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. import software.amazon.awssdk.services.iam.model.AttachedPermissionsBoundary; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.services.iam.model.ListUsersRequest; import software.amazon.awssdk.services.iam.model.ListUsersResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.User; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListUsers { public static void main(String[] args) { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); listAllUsers(iam); System.out.println("Done"); iam.close(); } 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); } } }-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK for Java 2.x Riferimento API.
-
- JavaScript
-
- SDK per JavaScript (v3)
-
Nota
C'è dell'altro GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. Elenca gli utenti.
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); for (const { UserName, CreateDate } of response.Users) { console.log(`${UserName} created on: ${CreateDate}`); } return response; };-
Per maggiori informazioni, consulta la Guida per sviluppatori di AWS SDK per JavaScript.
-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK per JavaScript Riferimento API.
-
- SDK per JavaScript (v2)
-
Nota
C'è dell'altro GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. // 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); }); } });-
Per maggiori informazioni, consulta la Guida per sviluppatori di AWS SDK per JavaScript.
-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK per JavaScript Riferimento API.
-
- Kotlin
-
- SDK per Kotlin
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. suspend fun listAllUsers() { IamClient.fromEnvironment { 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}") } } } }-
Per i dettagli sull'API, vedi ListUsers
nel AWS Riferimento all'API SDK per Kotlin.
-
- PHP
-
- SDK per PHP
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. $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); }-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK per PHP Riferimento API.
-
- PowerShell
-
- Utensili per PowerShell V4
-
Esempio 1: questo esempio recupera una raccolta di utenti nella versione corrente Account AWS.
Get-IAMUserListOutput:
Arn : arn:aws:iam::123456789012:user/Administrator CreateDate : 10/16/2014 9:03:09 AM PasswordLastUsed : 3/4/2015 12:12:33 PM Path : / UserId : 7K3GJEANSKZF2EXAMPLE1 UserName : Administrator Arn : arn:aws:iam::123456789012:user/Bob CreateDate : 4/6/2015 12:54:42 PM PasswordLastUsed : 1/1/0001 12:00:00 AM Path : / UserId : L3EWNONDOM3YUEXAMPLE2 UserName : bab Arn : arn:aws:iam::123456789012:user/David CreateDate : 12/10/2014 3:39:27 PM PasswordLastUsed : 3/19/2015 8:44:04 AM Path : / UserId : Y4FKWQCXTA52QEXAMPLE3 UserName : David-
Per i dettagli sull'API, vedi ListUsers nel AWS Strumenti per PowerShell Riferimento al cmdlet (V4).
-
- Utensili per PowerShell V5
-
Esempio 1: questo esempio recupera una raccolta di utenti nella versione corrente Account AWS.
Get-IAMUserListOutput:
Arn : arn:aws:iam::123456789012:user/Administrator CreateDate : 10/16/2014 9:03:09 AM PasswordLastUsed : 3/4/2015 12:12:33 PM Path : / UserId : 7K3GJEANSKZF2EXAMPLE1 UserName : Administrator Arn : arn:aws:iam::123456789012:user/Bob CreateDate : 4/6/2015 12:54:42 PM PasswordLastUsed : 1/1/0001 12:00:00 AM Path : / UserId : L3EWNONDOM3YUEXAMPLE2 UserName : bab Arn : arn:aws:iam::123456789012:user/David CreateDate : 12/10/2014 3:39:27 PM PasswordLastUsed : 3/19/2015 8:44:04 AM Path : / UserId : Y4FKWQCXTA52QEXAMPLE3 UserName : David-
Per i dettagli sull'API, vedi ListUsers nel AWS Strumenti per PowerShell Riferimento al cmdlet (V5).
-
- Python
-
- SDK per Python (Boto3)
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. 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-
Per i dettagli sull'API, vedi ListUsers nel AWS Riferimento alle API SDK per Python (Boto3).
-
- Ruby
-
- SDK per Ruby
-
Nota
C'è di più su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. # Lists all users in the AWS account # # @return [Array<Aws::IAM::Types::User>] An array of user objects def list_users users = [] @iam_client.list_users.each_page do |page| page.users.each do |user| users << user end end users rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing users: #{e.message}") [] end-
Per i dettagli sull'API, vedi ListUsers nel AWS SDK per Ruby Riferimento API.
-
- Rust
-
- SDK per Rust
-
Nota
C'è altro su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. 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) }-
Per i dettagli sull'API, vedi ListUsers
nel AWS SDK per Rust API di riferimento.
-
- SAP ABAP
-
- SDK per SAP ABAP
-
Nota
C'è altro su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. TRY. oo_result = lo_iam->listusers( ). MESSAGE 'Retrieved user list.' TYPE 'I'. CATCH /aws1/cx_iamservicefailureex. MESSAGE 'Service failure when listing users.' TYPE 'E'. ENDTRY.-
Per i dettagli sull'API, vedi ListUsers nel AWS Riferimento all'API SDK per SAP ABAP.
-
- Swift
-
- SDK per Swift
-
Nota
C'è altro su GitHub. Trova l’esempio completo e scopri di più sulla configurazione e l’esecuzione nel repository di esempi di codice AWS
. import AWSIAM import AWSS3 public func listUsers() async throws -> [MyUserRecord] { var userList: [MyUserRecord] = [] // Use "Paginated" to get all the users. // This lets the SDK handle the 'isTruncated' in "ListUsersOutput". let input = ListUsersInput() let output = client.listUsersPaginated(input: input) do { for try await page in output { guard let users = page.users else { continue } for user in users { if let id = user.userId, let name = user.userName { userList.append(MyUserRecord(id: id, name: name)) } } } } catch { print("ERROR: listUsers:", dump(error)) throw error } return userList }-
Per i dettagli sull'API, vedi ListUsers
nel AWS Riferimento SDK per Swift API.
-
Per un elenco completo di AWS Guide per sviluppatori SDK ed esempi di codice, consulta L'utilizzo di questo servizio con un AWS SDK. Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.