View a markdown version of this page

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

HeadBucket 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 HeadBucket

Bash
Amazon CLI 及 Bash 脚本
注意

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

############################################################################### # function bucket_exists # # This function checks to see if the specified bucket already exists. # # Parameters: # $1 - The name of the bucket to check. # # Returns: # 0 - If the bucket already exists. # 1 - If the bucket doesn't exist. ############################################################################### function bucket_exists() { local bucket_name bucket_name=$1 # Check whether the bucket already exists. # We suppress all output - we're interested only in the return code. if aws s3api head-bucket \ --bucket "$bucket_name" \ >/dev/null 2>&1; then return 0 # 0 in Bash script means true. else return 1 # 1 in Bash script means false. fi }
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 HeadBucket

CLI
Amazon CLI

以下命令验证对名为 amzn-s3-demo-bucket 的存储桶的访问权限:

aws s3api head-bucket --bucket amzn-s3-demo-bucket

如果存储桶存在并且您可以访问它,则不返回任何输出。否则,会显示错误消息。例如:

A client error (404) occurred when calling the HeadBucket operation: Not Found
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 HeadBucket

Go
适用于 Go 的 SDK V2
注意

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

import ( "bytes" "context" "errors" "fmt" "io" "log" "os" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/aws/smithy-go" ) // 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 } // BucketExists checks whether a bucket exists in the current account. func (basics BucketBasics) BucketExists(ctx context.Context, bucketName string) (bool, error) { _, err := basics.S3Client.HeadBucket(ctx, &s3.HeadBucketInput{ Bucket: aws.String(bucketName), }) exists := true if err != nil { var apiError smithy.APIError if errors.As(err, &apiError) { switch apiError.(type) { case *types.NotFound: log.Printf("Bucket %v is available.\n", bucketName) exists = false err = nil default: log.Printf("Either you don't have access to bucket %v or another error occurred. "+ "Here's what happened: %v\n", bucketName, err) } } } else { log.Printf("Bucket %v exists and you already own it.", bucketName) } return exists, err }
  • 有关 API 详细,请参阅《适用于 Go 的 Amazon SDK API Reference》中的 HeadBucket

PowerShell
适用于 PowerShell V5 的工具

示例 1:当用户有权访问现有存储桶时,此命令对于该存储桶返回带有 HTTP 状态代码 200 OK 的输出。只有 S3 目录存储桶支持 BucketArn 参数。

Get-S3HeadBucket -BucketName amzn-s3-demo-bucket

输出:

AccessPointAlias : False BucketArn : BucketLocationName : BucketLocationType : BucketRegion : us-east-2 ResponseMetadata : Amazon.Runtime.ResponseMetadata ContentLength : 0 HttpStatusCode : OK

示例 2:对于不存在的存储桶,此命令会引发错误,并显示 HTTP 状态代码 NotFound。

Get-S3HeadBucket -BucketName amzn-s3-non-existing-bucket

输出:

Get-S3HeadBucket: Error making request with Error Code NotFound and Http Status Code NotFound. No further error information was returned by the service.

示例 3:对于用户无权访问的现有存储桶,此命令会引发错误,并显示 HTTP 状态代码 Forbidden。

Get-S3HeadBucket -BucketName amzn-s3-no-access-bucket

输出:

Get-S3HeadBucket: Error making request with Error Code Forbidden and Http Status Code Forbidden. No further error information was returned by the service.
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet Reference (V5)》中的 HeadBucket

Python
适用于 Python 的 SDK(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 def exists(self): """ Determine whether the bucket exists and you have access to it. :return: True when the bucket exists; otherwise, False. """ try: self.bucket.meta.client.head_bucket(Bucket=self.bucket.name) logger.info("Bucket %s exists.", self.bucket.name) exists = True except ClientError: logger.warning( "Bucket %s doesn't exist or you don't have access to it.", self.bucket.name, ) exists = False return exists
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API Reference》中的 HeadBucket

SAP ABAP
适用于 SAP ABAP 的 SDK
注意

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

TRY. oo_result = lo_s3->headbucket( " oo_result is returned for testing purposes. " iv_bucket = iv_bucket_name ). MESSAGE 'Bucket exists and you have access to it.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. ENDTRY.
  • 有关 API 详细信息,请参阅《Amazon SDK for SAP ABAP API Reference》中的 HeadBucket

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 使用 Amazon SDK 通过 Amazon S3 进行开发。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。