如何使用boto3查找S3每个桶的大小

How to find the size of each bucket of S3 using boto3

我想计算每个 s3 桶的大小并生成这样的结果

Bucket_name total size
('bucket_A ', 0)
('Bucket_B', 51090)

这是我目前尝试的方法:

import boto3 
total_size = 0 
s3=boto3.resource('s3') 
for mybucket in s3.buckets.all(): 
  mybucket_size=sum([object.size for object in boto3.resource('s3').Bucket(mybucket.name).objects.all()]) 
print (mybucket.name, mybucket_size)

只需遍历所有对象并计算大小

sum([object.size for object in boto3.resource('s3').Bucket('mybucket').objects.all()])

编辑:

如果您希望它更快,则必须使用不同的方法,上面的方法是对存储桶中的每个对象发出 HTTP 请求,因此很明显它会随着存储桶中文件的数量线性扩展。不幸的是,这无法加速。

但是,您可以使用 third-party 脚本,例如 s4cmd,它比第一种方法更快。

s4cmd du s3://bucket-name

如果要包含子目录的大小,请使用 -r

s4cmd du -r s3://bucket-name

Amazon CloudWatch 自动收集 Amazon S3 上的指标,包括 BucketSizeBytes:

The amount of data in bytes stored in a bucket in the STANDARD storage class, INTELLIGENT_TIERING storage class, Standard - Infrequent Access (STANDARD_IA) storage class, OneZone - Infrequent Access (ONEZONE_IA), Reduced Redundancy Storage (RRS) class, or Glacier (GLACIER) storage class. This value is calculated by summing the size of all objects in the bucket (both current and noncurrent objects), including the size of all parts for all incomplete multipart uploads to the bucket.

参见:Monitoring Metrics with Amazon CloudWatch - Amazon Simple Storage Service