除非我遗漏了什么,否则我所看过的所有api似乎都不会告诉您<S3 bucket>/<文件夹>中有多少对象。有办法统计一下吗?


当前回答

@Mayank Jaiswal提到的关于使用cloudwatch指标的问题实际上不应该是一个问题。如果你没有得到结果,那可能是因为你的范围不够广。现在是11月3日,无论我做什么尝试,我都没有得到结果。我打开s3桶,查看计数,“对象总数”计数的最后一个记录是11月1日。

下面是cloudwatch解决方案使用javascript aws-sdk的样子:

import aws from 'aws-sdk';
import { startOfMonth } from 'date-fns';

const region = 'us-east-1';
const profile = 'default';
const credentials = new aws.SharedIniFileCredentials({ profile });
aws.config.update({ region, credentials });

export const main = async () => {
  const cw = new aws.CloudWatch();
  const bucket_name = 'MY_BUCKET_NAME';

  const end = new Date();
  const start = startOfMonth(end);

  const results = await cw
    .getMetricStatistics({
      // @ts-ignore
      Namespace: 'AWS/S3',
      MetricName: 'NumberOfObjects',
      Period: 3600 * 24,
      StartTime: start.toISOString(),
      EndTime: end.toISOString(),
      Statistics: ['Average'],
      Dimensions: [
        { Name: 'BucketName', Value: bucket_name },
        { Name: 'StorageType', Value: 'AllStorageTypes' },
      ],
      Unit: 'Count',
    })
    .promise();

  console.log({ results });
};

main()
  .then(() => console.log('Done.'))
  .catch((err) => console.error(err));

请注意两点:

范围的开始被设置为月初 周期设置为一天。如果少了一点,您可能会得到一个错误,说您请求了太多的数据点。

其他回答

旧线程,但仍然相关,因为我正在寻找答案,直到我明白了这一点。我想使用基于gui的工具(即没有代码)进行文件计数。我碰巧已经使用了一个名为3Hub的工具,用于在S3之间进行拖放传输。我想知道我在一个特定的存储区中有多少文件(我不认为计费是按存储区划分的)。

So, using 3Hub, 
- list the contents of the bucket (looks basically like a finder or explorer window)
- go to the bottom of the list, click 'show all'
- select all (ctrl+a)
- choose copy URLs from right-click menu
- paste the list into a text file (I use TextWrangler for Mac) 
- look at the line count  

我在桶中有20521个文件,并且在不到一分钟的时间内完成了文件计数。

没有一个API会给你一个计数,因为真的没有任何亚马逊特定的API来做这件事。您只需运行一个list-contents并计算返回的结果的数量。

下面是上面嵌入的python脚本的boto3版本。

import sys
import boto3

s3 = boto3.resource("s3")
s3bucket = s3.Bucket(sys.argv[1])
size = 0
totalCount = 0

for key in s3bucket.objects.all():
    totalCount += 1
    size += key.size

print("total size:")
print("%.3f GB" % (size * 1.0 / 1024 / 1024 / 1024))
print("total count:")
print(totalCount)

虽然这是一个老问题,并且反馈是在2015年提供的,但现在它要简单得多,因为S3 Web控制台启用了“获取大小”选项:

它提供了以下内容:

使用AWS CLI

aws s3 ls s3://mybucket/ --recursive | wc -l 

or

aws cloudwatch get-metric-statistics \
  --namespace AWS/S3 --metric-name NumberOfObjects \
  --dimensions Name=BucketName,Value=BUCKETNAME \
              Name=StorageType,Value=AllStorageTypes \
  --start-time 2016-11-05T00:00 --end-time 2016-11-05T00:10 \
  --period 60 --statistic Average

注意:上面的cloudwatch命令似乎适用于某些人,而不适用于其他人。讨论地点:https://forums.aws.amazon.com/thread.jspa?threadID=217050

使用AWS Web控制台

您可以查看cloudwatch的度量部分,以获得存储的对象的大约数量。

我有大约5000万个产品,使用aws s3 ls花了一个多小时来计数