boto3如何解析策略文档响应

How to parse the policy document response by boto3

我正在编写 python 扫描所有 S3 存储桶和文件的脚本。我希望脚本记录在策略文档中公开给 public 的每个文件,我的意思是它有:"Effect": "Allow""Principal" : "*"。所以我的代码中有这一行:

bucket_policy = storageClient.get_bucket_policy(Bucket='mybucket-documents-2017')
print(bucket_policy)

它returns一个字符串:

{
'Policy':
 u'{
 "Version":"2012-10-17",
 "Statement":[
 {
 "Sid":"",
 "Effect":"Allow",
 "Principal":
 {"AWS":"arn:aws:iam::000000000000:user/myuser"},
 "Action":"s3:GetObject",
 "Resource":"arn:aws:s3:::mybucket-documents-2017/*"
 },
 {
 "Sid":"",
 "Effect":"Allow",
 "Principal":{"AWS":"arn:aws:iam::0000000000000:user/myuser"},
 "Action":"s3:PutObject",
 "Resource":"arn:aws:s3:::mybucket-documents-2017/*"
 }]
 }', 
 'ResponseMetadata': {
 'HTTPStatusCode': 200, 'RetryAttempts': 0, 'HostId': '0EkHM/G1rnRjZH3lhTim1uaDG+5dCJmbJAhSVTnniGsNZIAl6SOMlYgbJOR0XAJOtzmXuu/CSd0=', 'RequestId': '037CADEB6342E9C
2', 'HTTPHeaders': {'x-amz-id-2': '0EkHM/G1rnRjZH3lhTim1uaDG+5dCJmbJAhSVTnniGsNZIAl6SOMlYgbJOR0XAJOtzmXuu/CSd0=', 'server': 'AmazonS3', 'transfer-encoding': 'chunked', 'x-amz-request-id': '037CADEB634
2E9C2', 'date': 'Fri, 11 Aug 2017 10:03:21 GMT', 'content-type': 'application/json'}
}

}

当我做类似的事情时:

 for policy in bucket_policy:
        print(policy[0])

for policy in bucket_policy['Policy']:
        print(policy[0])

我什么都没得到。

如何通过解析策略文档获取EffectPrincipal的值?

您可能希望首先将该字符串加载到本机数据类型中:

import json
policy = json.loads(bucket_policy['Policy'])

这将允许您遍历 Statement 数组。

for statement in policy['statement']:
    print(statement['Effect'])