将 ListBuckets 与 Amazon SDK 或命令行工具结合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

ListBuckets 与 Amazon SDK 或命令行工具结合使用

以下代码示例显示如何使用 ListBuckets

.NET
Amazon SDK for .NET
注意

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

namespace ListBucketsExample { using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example uses the AWS SDK for .NET to list the Amazon Simple Storage /// Service (Amazon S3) buckets belonging to the default account. /// </summary> public class ListBuckets { private static IAmazonS3 _s3Client; /// <summary> /// Get a list of the buckets owned by the default user. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <returns>The response from the ListingBuckets call that contains a /// list of the buckets owned by the default user.</returns> public static async Task<ListBucketsResponse> GetBuckets(IAmazonS3 client) { return await client.ListBucketsAsync(); } /// <summary> /// This method lists the name and creation date for the buckets in /// the passed List of S3 buckets. /// </summary> /// <param name="bucketList">A List of S3 bucket objects.</param> public static void DisplayBucketList(List<S3Bucket> bucketList) { bucketList .ForEach(b => Console.WriteLine($"Bucket name: {b.BucketName}, created on: {b.CreationDate}")); } public static async Task Main() { // The client uses the AWS Region of the default user. // If the Region where the buckets were created is different, // pass the Region to the client constructor. For example: // _s3Client = new AmazonS3Client(RegionEndpoint.USEast1); _s3Client = new AmazonS3Client(); var response = await GetBuckets(_s3Client); DisplayBucketList(response.Buckets); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 ListBuckets

C++
适用于 C++ 的 SDK
注意

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

bool AwsDoc::S3::ListBuckets(const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); auto outcome = client.ListBuckets(); bool result = true; if (!outcome.IsSuccess()) { std::cerr << "Failed with error: " << outcome.GetError() << std::endl; result = false; } else { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto &&b: outcome.GetResult().GetBuckets()) { std::cout << b.GetName() << std::endl; } } return result; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 ListBuckets

CLI
Amazon CLI

以下命令使用 list-buckets 命令显示所有 Amazon S3 存储桶的名称(跨所有区域):

aws s3api list-buckets --query "Buckets[].Name"

查询选项会筛选 list-buckets 的输出,使其范围缩小到仅限存储桶名称。

有关存储桶的更多信息,请参阅《Amazon S3 开发人员指南》中的“使用 Amazon S3 存储桶”。

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 ListBuckets

Go
适用于 Go V2 的 SDK
注意

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

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // ListBuckets lists the buckets in the current account. func (basics BucketBasics) ListBuckets() ([]types.Bucket, error) { result, err := basics.S3Client.ListBuckets(context.TODO(), &s3.ListBucketsInput{}) var buckets []types.Bucket if err != nil { log.Printf("Couldn't list buckets for your account. Here's why: %v\n", err) } else { buckets = result.Buckets } return buckets, err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 ListBuckets

Java
SDK for Java 2.x
注意

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

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.Bucket; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; import java.util.List; /** * 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 ListBuckets { public static void main(String[] args) { Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); listAllBuckets(s3); } public static void listAllBuckets(S3Client s3) { ListBucketsResponse response = s3.listBuckets(); List<Bucket> bucketList = response.buckets(); for (Bucket bucket: bucketList) { System.out.println("Bucket name "+bucket.name()); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 ListBuckets

JavaScript
SDK for JavaScript (v3)
注意

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

列出存储桶。

import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new ListBucketsCommand({}); try { const { Owner, Buckets } = await client.send(command); console.log( `${Owner.DisplayName} owns ${Buckets.length} bucket${ Buckets.length === 1 ? "" : "s" }:`, ); console.log(`${Buckets.map((b) => ` • ${b.Name}`).join("\n")}`); } catch (err) { console.error(err); } };
PowerShell
适用于 PowerShell 的工具

示例 1:此命令返回所有 S3 存储桶。

Get-S3Bucket

示例 2:此命令返回名为“test-files”的存储桶

Get-S3Bucket -BucketName test-files
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 ListBuckets

Python
SDK for Python(Boto3)
注意

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

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name @staticmethod def list(s3_resource): """ Get the buckets in all Regions for the current account. :param s3_resource: A Boto3 S3 resource. This is a high-level resource in Boto3 that contains collections and factory methods to create other high-level S3 sub-resources. :return: The list of buckets. """ try: buckets = list(s3_resource.buckets.all()) logger.info("Got buckets: %s.", buckets) except ClientError: logger.exception("Couldn't get buckets.") raise else: return buckets
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 ListBuckets

Ruby
适用于 Ruby 的 SDK
注意

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

require "aws-sdk-s3" # Wraps Amazon S3 resource actions. class BucketListWrapper attr_reader :s3_resource # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def initialize(s3_resource) @s3_resource = s3_resource end # Lists buckets for the current account. # # @param count [Integer] The maximum number of buckets to list. def list_buckets(count) puts "Found these buckets:" @s3_resource.buckets.each do |bucket| puts "\t#{bucket.name}" count -= 1 break if count.zero? end true rescue Aws::Errors::ServiceError => e puts "Couldn't list buckets. Here's why: #{e.message}" false end end # Example usage: def run_demo wrapper = BucketListWrapper.new(Aws::S3::Resource.new) wrapper.list_buckets(25) end run_demo if $PROGRAM_NAME == __FILE__
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 ListBuckets

Rust
适用于 Rust 的 SDK
注意

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

async fn show_buckets(strict: bool, client: &Client, region: &str) -> Result<(), Error> { let resp = client.list_buckets().send().await?; let buckets = resp.buckets(); let num_buckets = buckets.len(); let mut in_region = 0; for bucket in buckets { if strict { let r = client .get_bucket_location() .bucket(bucket.name().unwrap_or_default()) .send() .await?; if r.location_constraint().unwrap().as_ref() == region { println!("{}", bucket.name().unwrap_or_default()); in_region += 1; } } else { println!("{}", bucket.name().unwrap_or_default()); } } println!(); if strict { println!( "Found {} buckets in the {} region out of a total of {} buckets.", in_region, region, num_buckets ); } else { println!("Found {} buckets in all regions.", num_buckets); } Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 ListBuckets

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

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

/// Return an array containing information about every available bucket. /// /// - Returns: An array of ``S3ClientTypes.Bucket`` objects describing /// each bucket. public func getAllBuckets() async throws -> [S3ClientTypes.Bucket] { let output = try await client.listBuckets(input: ListBucketsInput()) guard let buckets = output.buckets else { return [] } return buckets }
  • 有关 API 详细信息,请参阅《Amazon SDK for Swift API 参考》中的 ListBuckets

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