如何使用Boto3和AWS客户端获取S3存储桶的日志详细信息?
问题陈述 − 使用 Python 中的 boto3 库获取 S3 存储桶的日志详细信息。例如,在 S3 中查找 Bucket_1 的日志详细信息。
阅读更多:Python 教程
解决此问题的方法/算法
步骤 1 − 导入 boto3 和 botocore 异常以处理异常。
步骤 2 − 使用 bucket_name 作为函数的参数。
步骤 3 − 使用 boto3 库创建 AWS 会话。
步骤 4 − 为 S3 创建 AWS 客户端。
步骤 5 − 现在使用函数 get_bucket_logging,并传递存储桶名称。
步骤 6 − 它返回一个包含有关 S3 的详细信息的字典。
步骤 7 − 处理通用异常,如果在删除文件时出现了错误。
例子
使用以下代码获取存储桶的日志详细信息 −
import boto3
from botocore.exceptions import ClientError
def get_bucket_logging_of_s3(bucket_name):
session = boto3.session.Session()
s3_client = session.client('s3')
try:
result = s3_client.get_bucket_logging(Bucket=bucket_name,)
except ClientError as e:
raise Exception( "boto3 client error in get_bucket_logging_of_s3: " + e.__str__())
except Exception as e:
raise Exception( "Unexpected error in get_bucket_logging_of_s3 function: " + e.__str__())
return result
print(get_bucket_logging_of_s3("Bucket_1"))
输出
{
'LoggingEnabled': {
'TargetBucket': 'string',
'TargetGrants': [
{
'Grantee': {
'DisplayName': 'string',
'EmailAddress': 'string',
'ID': 'string',
'Type': 'CanonicalUser'|'AmazonCustomerByEmail'|'Group',
'URI': 'string'
},
'Permission': 'FULL_CONTROL'|'READ'|'WRITE'
},
],
'TargetPrefix': 'string'
}
}
极客教程