AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
与 AWS SDK或GetBucketPolicy
一起使用 CLI
以下代码示例演示如何使用 GetBucketPolicy
。
- C++
-
- SDK对于 C++
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 bool AwsDoc::S3::getBucketPolicy(const Aws::String &bucketName, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client s3Client(clientConfig); Aws::S3::Model::GetBucketPolicyRequest request; request.SetBucket(bucketName); Aws::S3::Model::GetBucketPolicyOutcome outcome = s3Client.GetBucketPolicy(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: getBucketPolicy: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { Aws::StringStream policy_stream; Aws::String line; outcome.GetResult().GetPolicy() >> line; policy_stream << line; std::cout << "Retrieve the policy for bucket '" << bucketName << "':\n\n" << policy_stream.str() << std::endl; } return outcome.IsSuccess(); }
-
有关API详细信息,请参阅 “AWS SDK for C++ API参考 GetBucketPolicy” 中的。
-
- CLI
-
- AWS CLI
-
以下命令检索名为
my-bucket
的存储桶的存储桶策略:aws s3api get-bucket-policy --bucket
my-bucket
输出:
{ "Policy": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::my-bucket/*\"},{\"Sid\":\"\",\"Effect\":\"Deny\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::my-bucket/secret/*\"}]}" }
获取并放置存储桶 policyThe 以下示例展示了如何下载 Amazon S3 存储桶策略,修改文件,然后使用
put-bucket-policy
来应用修改后的存储桶策略。要将存储桶策略下载到文件中,您可以运行:aws s3api get-bucket-policy --bucket mybucket --query Policy --output text > policy.json
然后,您可以根据需要修改
policy.json
文件。最后,您可以通过运行以下对象,将此修改后的策略应用回 S3 存储桶:policy.json
文件(根据需要)。最后,您可以通过运行以下对象,将此修改后的策略应用回 S3 存储桶:文件(根据需要)。最后,您可以通过运行以下对象,将此修改后的策略应用回 S3 存储桶:
aws s3api put-bucket-policy --bucket mybucket --policy file://policy.json
-
有关API详细信息,请参阅AWS CLI 命令参考GetBucketPolicy
中的。
-
- Java
-
- SDK适用于 Java 2.x
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest; import software.amazon.awssdk.services.s3.model.GetBucketPolicyResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * <p> * For more information, see the following documentation topic: * <p> * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class GetBucketPolicy { public static void main(String[] args) { final String usage = """ Usage: <bucketName> Where: bucketName - The Amazon S3 bucket to get the policy from. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); String polText = getPolicy(s3, bucketName); System.out.println("Policy Text: " + polText); s3.close(); } /** * Retrieves the policy for the specified Amazon S3 bucket. * * @param s3 the {@link S3Client} instance to use for making the request * @param bucketName the name of the S3 bucket for which to retrieve the policy * @return the policy text for the specified bucket, or an empty string if an error occurs */ public static String getPolicy(S3Client s3, String bucketName) { String policyText; System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); GetBucketPolicyRequest policyReq = GetBucketPolicyRequest.builder() .bucket(bucketName) .build(); try { GetBucketPolicyResponse policyRes = s3.getBucketPolicy(policyReq); policyText = policyRes.policy(); return policyText; } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 GetBucketPolicy” 中的。
-
- JavaScript
-
- SDK对于 JavaScript (v3)
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 获取存储桶策略。
import { GetBucketPolicyCommand, S3Client, S3ServiceException, } from "@aws-sdk/client-s3"; /** * Logs the policy for a specified bucket. * @param {{ bucketName: string }} */ export const main = async ({ bucketName }) => { const client = new S3Client({}); try { const { Policy } = await client.send( new GetBucketPolicyCommand({ Bucket: bucketName, }), ); console.log(`Policy for "${bucketName}":\n${Policy}`); } catch (caught) { if ( caught instanceof S3ServiceException && caught.name === "NoSuchBucket" ) { console.error( `Error from S3 while getting policy from ${bucketName}. The bucket doesn't exist.`, ); } else if (caught instanceof S3ServiceException) { console.error( `Error from S3 while getting policy from ${bucketName}. ${caught.name}: ${caught.message}`, ); } else { throw caught; } } };
-
有关更多信息,请参阅 AWS SDK for JavaScript 开发人员指南。
-
有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 GetBucketPolicy” 中的。
-
- Kotlin
-
- SDK对于 Kotlin 来说
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 suspend fun getPolicy(bucketName: String): String? { println("Getting policy for bucket $bucketName") val request = GetBucketPolicyRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> val policyRes = s3.getBucketPolicy(request) return policyRes.policy } }
-
有关API详细信息,请参阅GetBucketPolicy
中的 Kotlin AWS SDK API 参考。
-
- PowerShell
-
- 用于 PowerShell
-
示例 1:此命令输出与给定 S3 存储桶关联的存储桶策略。
Get-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
-
有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考GetBucketPolicy中的。
-
- Python
-
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 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 get_policy(self): """ Get the security policy of the bucket. :return: The security policy of the specified bucket, in JSON format. """ try: policy = self.bucket.Policy() logger.info( "Got policy %s for bucket '%s'.", policy.policy, self.bucket.name ) except ClientError: logger.exception("Couldn't get policy for bucket '%s'.", self.bucket.name) raise else: return json.loads(policy.policy)
-
有关API详细信息,请参阅GetBucketPolicy中的 AWS SDKPython (Boto3) API 参考。
-
- Ruby
-
- SDK对于 Ruby
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 # Wraps an Amazon S3 bucket policy. class BucketPolicyWrapper attr_reader :bucket_policy # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket. def initialize(bucket_policy) @bucket_policy = bucket_policy end # Gets the policy of a bucket. # # @return [Aws::S3::GetBucketPolicyOutput, nil] The current bucket policy. def policy policy = @bucket_policy.data.policy policy.respond_to?(:read) ? policy.read : policy rescue Aws::Errors::ServiceError => e puts "Couldn't get the policy for #{@bucket_policy.bucket.name}. Here's why: #{e.message}" nil end end
-
有关API详细信息,请参阅 “AWS SDK for Ruby API参考 GetBucketPolicy” 中的。
-