我想从我拥有的所有s3存储桶中取出s3存储桶策略,并将它们存储在各自的.json文件中。这应该在json中格式化。但是,在我尝试的解决方案中,它将策略存储在具有Response元数据的文件中,而不是jSOn格式。
"ResponseMetadata": {"HTTPStatusCode": 200, ...... "content-type": "application/json"}}}
这可以在python / boto3中完成吗?这是我的代码。
try:
s3client = get_s3Client('us-east-1')
response = s3client.list_buckets()
if response and response['Buckets']:
for bucket in response['Buckets']:
bucketName = bucket['Name']
print (bucketName)
policyname = policy_output + '\\' + bucketName + '.json'
print (policyname)
response = s3client.get_bucket_policy(
Bucket=bucketName
)
print (response)
with open(policyname, 'w') as f:
json.dump(response, f)
#f.write(response)
答案 0 :(得分:3)
来自boto3 get_bucket_policy()的回复是一个字典。您需要检索政策'元件。
尝试这样的事情:
import json
import boto3
from botocore.exceptions import ClientError
s3client = boto3.client('s3')
response = s3client.list_buckets()
if response and response['Buckets']:
for bucket in response['Buckets']:
bucketName = bucket['Name']
print(bucketName)
policyname = bucketName + '.json'
print(policyname)
try:
response = s3client.get_bucket_policy(
Bucket=bucketName
)
p = response['Policy']
s = json.dumps(json.loads(p), indent=4)
with open(policyname, 'w') as f:
f.write(s)
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucketPolicy':
pass
else:
print(e)