Answers:
from boto.s3.connection import S3Connection
conn = S3Connection('access-key','secret-access-key')
bucket = conn.get_bucket('bucket')
for key in bucket.list():
print key.name.encode('utf-8')
将此另存为list.py,打开一个终端,然后运行:
$ python list.py > results.txt
AWS最近发布了其命令行工具。此工作原理与boto非常相似,可以使用sudo easy_install awscli
或安装sudo pip install awscli
安装完成后,您就可以直接运行
aws s3 ls
它将向您显示所有可用的存储桶
CreationTime Bucket
------------ ------
2013-07-11 17:08:50 mybucket
2013-07-24 14:55:44 mybucket2
然后,您可以查询特定存储桶中的文件。
命令:
aws s3 ls s3://mybucket
输出:
Bucket: mybucket
Prefix:
LastWriteTime Length Name
------------- ------ ----
PRE somePrefix/
2013-07-25 17:06:27 88 test.txt
这将显示所有文件。
--recursive
标志以查看指定目录下的所有对象
请注意,亚马逊列表仅返回1000个文件。如果要遍历所有文件,则必须使用标记对结果进行分页:
在红宝石中使用AWS-S3
bucket_name = 'yourBucket'
marker = ""
AWS::S3::Base.establish_connection!(
:access_key_id => 'your_access_key_id',
:secret_access_key => 'your_secret_access_key'
)
loop do
objects = Bucket.objects(bucket_name, :marker=>marker, :max_keys=>1000)
break if objects.size == 0
marker = objects.last.key
objects.each do |obj|
puts "#{obj.key}"
end
end
结束
希望对你有帮助,文森特
更新15-02-2019:
该命令将为您提供AWS S3中所有存储桶的列表:
aws s3 ls
该命令将为您提供AWS S3存储桶中所有顶级对象的列表:
aws s3 ls bucket-name
该命令将为您提供AWS S3存储桶中所有对象的列表:
aws s3 ls bucket-name --recursive
此命令会将所有列表放在AWS S3存储桶中...当前目录中的文本文件中:
aws s3 ls bucket-name --recursive | cat >> file-name.txt
对于Scala开发人员来说,这是递归函数,它使用官方的Java Java开发工具包SDK执行完整扫描并映射 AmazonS3存储桶的内容
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.{S3ObjectSummary, ObjectListing, GetObjectRequest}
import scala.collection.JavaConversions.{collectionAsScalaIterable => asScala}
def map[T](s3: AmazonS3Client, bucket: String, prefix: String)(f: (S3ObjectSummary) => T) = {
def scan(acc:List[T], listing:ObjectListing): List[T] = {
val summaries = asScala[S3ObjectSummary](listing.getObjectSummaries())
val mapped = (for (summary <- summaries) yield f(summary)).toList
if (!listing.isTruncated) mapped.toList
else scan(acc ::: mapped, s3.listNextBatchOfObjects(listing))
}
scan(List(), s3.listObjects(bucket, prefix))
}
要调用上述curried map()
函数,只需在第一个参数列表中传递已构造(并正确初始化)的AmazonS3Client对象(请参阅Java API的官方AWS开发工具包参考),存储桶名称和前缀名称。还要传递f()
您要应用的函数以映射第二个参数列表中的每个对象摘要。
例如
val keyOwnerTuples = map(s3, bucket, prefix)(s => (s.getKey, s.getOwner))
将返回该(key, owner)
存储桶/前缀中元组的完整列表
要么
map(s3, "bucket", "prefix")(s => println(s))
正如您通常在函数式编程中Monads所采用的那样
mapped.toList
不包含任何先前的结果而返回acc
有几种方法可以解决此问题。使用Python
import boto3
sesssion = boto3.Session(aws_access_key_id, aws_secret_access_key)
s3 = sesssion.resource('s3')
bucketName = 'testbucket133'
bucket = s3.Bucket(bucketName)
for obj in bucket.objects.all():
print(obj.key)
另一种方法是使用AWS CLI
aws s3 ls s3://{bucketname}
example : aws s3 ls s3://testbucket133
s3 = boto3.resource('s3')
session
方法中使用变量。 AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
aws s3api list-objects --bucket bucket-name
有关更多详细信息,请参见此处-http://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html
aws s3api list-objects --bucket <bucket-name>
首先要确认你是一个instance terminal
和你all access
的S3
在IAM
你使用。例如,我使用了一个ec2实例。
pip3 install awscli
然后配置aws
aws configure
然后填写excredantials例如:
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json (or just press enter)
现在,查看所有存储桶
aws s3 ls
存储所有存储桶名称
aws s3 ls > output.txt
查看存储桶中的所有文件结构
aws s3 ls bucket-name --recursive
将文件结构存储在每个存储桶中
aws s3 ls bucket-name --recursive > file_Structure.txt
希望这可以帮助。
在Java中,您可以使用ListObjects获取密钥(请参阅AWS文档)
FileWriter fileWriter;
BufferedWriter bufferedWriter;
// [...]
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("myprefix");
ObjectListing objectListing;
do {
objectListing = s3client.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary :
objectListing.getObjectSummaries()) {
// write to file with e.g. a bufferedWriter
bufferedWriter.write(objectSummary.getKey());
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
使用很棒的“ boto” lib在python中进行编码。该代码返回存储桶中的文件列表,并处理丢失的存储桶的异常。
import boto
conn = boto.connect_s3( <ACCESS_KEY>, <SECRET_KEY> )
try:
bucket = conn.get_bucket( <BUCKET_NAME>, validate = True )
except boto.exception.S3ResponseError, e:
do_something() # The bucket does not exist, choose how to deal with it or raise the exception
return [ key.name.encode( "utf-8" ) for key in bucket.list() ]
不要忘记用您的值替换<PLACE_HOLDERS>。
以下命令将从您的AWS S3存储桶中获取所有文件名,并将其写入当前目录中的文本文件:
aws s3 ls s3://Bucketdirectory/Subdirectory/ | cat >> FileNames.txt
或者,您可以使用Minio Client aka mc。它是开源的,并且与AWS S3兼容。它适用于Linux,Windows,Mac,FreeBSD。
您要做的就是运行mc ls命令列出内容。
$ mc ls s3 / kline / [2016-04-30 13:20:47 IST] 1.1MiB 1.jpg [2016-04-30 16:03:55 IST] 7.5KiB docker.png [2016-04-30 15:16:17 IST] 50KiB pi.png [2016-05-10 14:34:39 IST] 365KiB upton.pdf
注意:
安装Minio Client Linux 下载mc用于:
$ chmod 755 mc $ ./mc-帮助
使用Minio Client设置AWS凭证
$ mc配置主机添加mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
注意:请使用您要为此帐户使用的别名替换mys3,并使用AWS ACCESS-KEY和SECRET-KEY替换,BKIKJAA5BMMU2RHO6IBB,V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
希望能帮助到你。
免责声明:我为Minio工作
您可以使用以下命令在aws s3存储桶中列出所有文件:
aws s3 ls path/to/file
并将其保存在文件中,请使用
aws s3 ls path/to/file >> save_result.txt
如果要将结果附加到文件中,则:
aws s3 ls path/to/file > save_result.txt
如果您想清除以前写的内容。
它可以在Windows和Linux中使用。
在javascript中,您可以使用
s3.listObjects(params,function(err,result){});
将所有对象放入存储桶中 您必须在参数内传递存储桶名称(存储桶:名称)。
function showUploads(){
if (!class_exists('S3')) require_once 'S3.php';
// AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', '234567665464tg');
if (!defined('awsSecretKey')) define('awsSecretKey', 'dfshgfhfghdgfhrt463457');
$bucketName = 'my_bucket1234';
$s3 = new S3(awsAccessKey, awsSecretKey);
$contents = $s3->getBucket($bucketName);
echo "<hr/>List of Files in bucket : {$bucketName} <hr/>";
$n = 1;
foreach ($contents as $p => $v):
echo $p."<br/>";
$n++;
endforeach;
}
# find like file listing for s3 files
aws s3api --profile <<profile-name>> \
--endpoint-url=<<end-point-url>> list-objects \
--bucket <<bucket-name>> --query 'Contents[].{Key: Key}'
Paolo的Scala答案的简化和更新版本:
import scala.collection.JavaConversions.{collectionAsScalaIterable => asScala}
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.model.{ListObjectsRequest, ObjectListing, S3ObjectSummary}
def buildListing(s3: AmazonS3, request: ListObjectsRequest): List[S3ObjectSummary] = {
def buildList(listIn: List[S3ObjectSummary], bucketList:ObjectListing): List[S3ObjectSummary] = {
val latestList: List[S3ObjectSummary] = bucketList.getObjectSummaries.toList
if (!bucketList.isTruncated) listIn ::: latestList
else buildList(listIn ::: latestList, s3.listNextBatchOfObjects(bucketList))
}
buildList(List(), s3.listObjects(request))
}
剥离泛型并使用由SDK构建器生成的ListObjectRequest。
public static Dictionary<string, DateTime> ListBucketsByCreationDate(string AccessKey, string SecretKey)
{
return AWSClientFactory.CreateAmazonS3Client(AccessKey,
SecretKey).ListBuckets().Buckets.ToDictionary(s3Bucket => s3Bucket.BucketName,
s3Bucket => DateTime.Parse(s3Bucket.CreationDate));
}
在PHP中,您可以使用以下调用获取特定存储桶内的AWS-S3对象的完整列表
$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
echo $obj['Key'];
}
您可以将上述代码的输出重定向到文件中以获取密钥列表。
使用铅包起cli,您将拥有清晰的语法:
import plumbum as pb
folders = pb.local['aws']('s3', 'ls')
请尝试此bash脚本。它使用curl命令,不需要任何外部依赖
bucket=<bucket_name>
region=<region_name>
awsAccess=<access_key>
awsSecret=<secret_key>
awsRegion="${region}"
baseUrl="s3.${awsRegion}.amazonaws.com"
m_sed() {
if which gsed > /dev/null 2>&1; then
gsed "$@"
else
sed "$@"
fi
}
awsStringSign4() {
kSecret="AWS4$1"
kDate=$(printf '%s' "$2" | openssl dgst -sha256 -hex -mac HMAC -macopt "key:${kSecret}" 2>/dev/null | m_sed 's/^.* //')
kRegion=$(printf '%s' "$3" | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kDate}" 2>/dev/null | m_sed 's/^.* //')
kService=$(printf '%s' "$4" | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kRegion}" 2>/dev/null | m_sed 's/^.* //')
kSigning=$(printf 'aws4_request' | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kService}" 2>/dev/null | m_sed 's/^.* //')
signedString=$(printf '%s' "$5" | openssl dgst -sha256 -hex -mac HMAC -macopt "hexkey:${kSigning}" 2>/dev/null | m_sed 's/^.* //')
printf '%s' "${signedString}"
}
if [ -z "${region}" ]; then
region="${awsRegion}"
fi
# Initialize helper variables
authType='AWS4-HMAC-SHA256'
service="s3"
dateValueS=$(date -u +'%Y%m%d')
dateValueL=$(date -u +'%Y%m%dT%H%M%SZ')
# 0. Hash the file to be uploaded
# 1. Create canonical request
# NOTE: order significant in ${signedHeaders} and ${canonicalRequest}
signedHeaders='host;x-amz-content-sha256;x-amz-date'
canonicalRequest="\
GET
/
host:${bucket}.s3.amazonaws.com
x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-amz-date:${dateValueL}
${signedHeaders}
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
# Hash it
canonicalRequestHash=$(printf '%s' "${canonicalRequest}" | openssl dgst -sha256 -hex 2>/dev/null | m_sed 's/^.* //')
# 2. Create string to sign
stringToSign="\
${authType}
${dateValueL}
${dateValueS}/${region}/${service}/aws4_request
${canonicalRequestHash}"
# 3. Sign the string
signature=$(awsStringSign4 "${awsSecret}" "${dateValueS}" "${region}" "${service}" "${stringToSign}")
# Upload
curl -g -k "https://${baseUrl}/${bucket}" \
-H "x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" \
-H "x-amz-Date: ${dateValueL}" \
-H "Authorization: ${authType} Credential=${awsAccess}/${dateValueS}/${region}/${service}/aws4_request,SignedHeaders=${signedHeaders},Signature=${signature}"
获得非常有用的文本文件的最简便方法是下载S3浏览器http://s3browser.com/并使用Web URLs Generator生成完整链接路径的列表。这非常方便,大约需要点击3次。
-Browse to Folder
-Select All
-Generate Urls
祝您好运。
boto.s3.bucketlistresultset.BucketListResultSet
解决了问题中提到的“成千上万个文件名”的情况。