在AWS CLI和boto3中,可以使用aws iam simulate-principal-policy
命令和boto3
库中的iam.SimulatePrincipalPolicy()
方法来检查角色或策略是否对特定资源拥有权限。
AWS CLI示例:
aws iam simulate-principal-policy --policy-source-arn --action-names --resource-arns
:策略的ARN(Amazon Resource Name)。
:以逗号分隔的要检查的操作名称列表。
:以逗号分隔的要检查的资源ARN列表。如果命令的输出中包含"allowed": true
,则表示该角色或策略对该资源拥有权限。
boto3示例:
import boto3
def check_permission(policy_arn, actions, resources):
client = boto3.client('iam')
response = client.simulate_principal_policy(
PolicySourceArn=policy_arn,
ActionNames=actions,
ResourceArns=resources
)
for result in response['EvaluationResults']:
if result['EvalDecision'] == 'allowed':
print(f"Allowed: {result['EvalActionName']} on {result['EvalResourceName']}")
else:
print(f"Not allowed: {result['EvalActionName']} on {result['EvalResourceName']}")
# 调用示例
policy_arn = 'arn:aws:iam::123456789012:policy/ExamplePolicy'
actions = ['s3:GetObject', 's3:PutObject']
resources = ['arn:aws:s3:::example-bucket/example-file.txt']
check_permission(policy_arn, actions, resources)
以上示例中,policy_arn
是要检查的策略的ARN,actions
是要检查的操作名称列表,resources
是要检查的资源ARN列表。check_permission
函数将遍历模拟结果并打印出每个操作和资源的权限情况。
请根据实际情况替换示例中的策略ARN、操作名称和资源ARN。