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


当前回答

有一个——summary开关,显示桶的摘要信息(即对象的数量,总大小)。

下面是使用AWS cli的正确答案:

aws s3 ls s3://bucketName/path/ --recursive --summarize | grep "Total Objects:"

Total Objects: 194273

参见文档

其他回答

@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));

请注意两点:

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

2020/10/22

使用AWS控制台

查看bucket上的Metrics标签

or:

看看AWS Cloudwatch的指标

使用AWS CLI

对象数量:

or:

aws s3api list-objects --bucket <BUCKET_NAME> --prefix "<FOLDER_NAME>" | wc -l

or:

aws s3 ls s3://<BUCKET_NAME>/<FOLDER_NAME>/ --recursive --summarize --human-readable | grep "Total Objects"

或者用s4cmd:

s4cmd ls -r s3://<BUCKET_NAME>/<FOLDER_NAME>/ | wc -l

对象大小:

aws s3api list-objects --bucket <BUCKET_NAME> --output json --query "[sum(Contents[].Size), length(Contents[])]" | awk  'NR!=2 {print $0;next}  NR==2 {print $0/1024/1024/1024" GB"}'

or:

aws s3 ls s3://<BUCKET_NAME>/<FOLDER_NAME>/ --recursive --summarize --human-readable | grep "Total Size"

或者用s4cmd:

s4cmd du s3://<BUCKET_NAME>

或与CloudWatch指标:

aws cloudwatch get-metric-statistics --metric-name BucketSizeBytes --namespace AWS/S3 --start-time 2020-10-20T16:00:00Z --end-time 2020-10-22T17:00:00Z --period 3600 --statistics Average --unit Bytes --dimensions Name=BucketName,Value=<BUCKET_NAME> Name=StorageType,Value=StandardStorage --output json | grep "Average"

以下是如何使用java客户端。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
    <version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;

public class AmazonS3Service {

    private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
    private static final String S3_SECRET_KEY = "SECRET_KEY";
    private static final String S3_ENDPOINT = "S3_URL";

    private AmazonS3 amazonS3;

    public AmazonS3Service() {
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        clientConfiguration.setSignerOverride("S3SignerType");
        BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
        AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
        amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
                .withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
    }

    public int countObjects(String bucketName) {
        int count = 0;
        ObjectListing objectListing = amazonS3.listObjects(bucketName);
        int currentBatchCount = objectListing.getObjectSummaries().size();
        while (currentBatchCount != 0) {
            count += currentBatchCount;
            objectListing = amazonS3.listNextBatchOfObjects(objectListing);
            currentBatchCount = objectListing.getObjectSummaries().size();
        }
        return count;
    }
}

也可以用gsutil du(是的,一个谷歌云工具)

gsutil du s3://mybucket/ | wc -l

选择桶/文件夹->单击动作->单击计算总大小