除非我遗漏了什么,否则我所看过的所有api似乎都不会告诉您<S3 bucket>/<文件夹>中有多少对象。有办法统计一下吗?
当前回答
在AWS CLI的命令行中,使用ls加——summary。它将为您提供所有项目的列表以及特定bucket中的文档总数。我还没有尝试过包含子桶的桶:
aws s3 ls "s3://MyBucket" --summarize
这可能会花费一些时间(列出我16+K的文档大约需要4分钟),但这比一次计算1K要快。
其他回答
@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));
请注意两点:
范围的开始被设置为月初 周期设置为一天。如果少了一点,您可能会得到一个错误,说您请求了太多的数据点。
下面是上面嵌入的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)
以下是如何使用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;
}
}
在s3cmd中,简单地运行以下命令(在Ubuntu系统上):
s3cmd ls -r s3://mybucket | wc -l
如果使用s3cmd命令行工具,可以获得特定桶的递归列表,并将其输出到文本文件。
s3cmd ls -r s3://logs.mybucket/subfolder/ > listing.txt
然后在linux中,您可以对文件运行wc -l来计算行数(每个对象1行)。
wc -l listing.txt
推荐文章
- 如何查看所有地区所有正在运行的Amazon EC2实例?
- 确定记录是否存在的最快方法
- 如何在Python中获得所有直接子目录
- 如何从命令行使用多个AWS帐户?
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- 如何在Ruby中创建文件
- 使用LIMIT/OFFSET运行查询,还可以获得总行数
- __FILE__宏显示完整路径
- 如何搜索亚马逊s3桶?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 拒绝访问;您需要(至少一个)SUPER特权来执行此操作
- 我如何使用通配符“cp”一组文件与AWS CLI
- 如何删除文件中的特定行?
- 使用Java重命名文件
- 如何从Python包内读取(静态)文件?