IT박스

Amazon S3 버킷의 모든 파일을 나열하는 빠른 방법은 무엇입니까?

itboxs 2020. 6. 27. 11:48
반응형

Amazon S3 버킷의 모든 파일을 나열하는 빠른 방법은 무엇입니까?


수만 개의 파일 이름이있는 Amazon S3 버킷이 있습니다. 버킷의 모든 파일 이름을 나열하는 텍스트 파일을 얻는 가장 쉬운 방법은 무엇입니까?


boto 사용하는 것이 좋습니다 . 그런 다음 몇 줄의 파이썬입니다 .

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 CLI

AWS S3 LS에 대한 설명서

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

모든 파일이 표시됩니다.


s3cmd 는 이런 종류의 것에 매우 중요합니다

$ s3cmd ls -r s3://yourbucket/ | awk '{print $4}' > objects_in_bucket


아마존 목록은 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 버킷 내부의 ALL 목록을 현재 디렉토리의 텍스트 파일 내에 배치합니다.

aws s3 ls bucket-name --recursive | cat >> file-name.txt


스칼라 개발자 에게는 공식 AWS SDK for Java를 사용하여 전체 스캔 을 실행하고 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))
}

위의 커리 map()함수 를 호출하려면 첫 번째 파라미터 목록에서 이미 생성되고 올바르게 초기화 된 AmazonS3Client 객체 (공식 AWS SDK for Java API Reference 참조 ), 버킷 이름 및 접두사 이름을 전달하면됩니다. 또한 f()적용하려는 함수 전달하여 두 번째 매개 변수 목록에서 각 객체 요약을 매핑합니다.

예를 들어

val keyOwnerTuples = map(s3, bucket, prefix)(s => (s.getKey, s.getOwner))

(key, owner)해당 버킷 / 접두사 튜플 의 전체 목록을 반환합니다.

또는

map(s3, "bucket", "prefix")(s => println(s))

함수형 프로그래밍에서 Monads 가 일반적으로 접근하는 것처럼


zach 후 boto 도 추천 하지만 그의 코드와 약간의 차이를 만들어야했습니다.

conn = boto.connect_s3('access-key', 'secret'key')
bucket = conn.lookup('bucket-name')
for key in bucket:
    print key.name

aws s3api list-objects --bucket bucket-name

자세한 내용은 여기를 참조하십시오 -http : //docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html


당신이 그것에 대해 갈 수있는 몇 가지 방법이 있습니다. 파이썬 사용하기

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

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

사용 후 파이썬의 boto3의 경우 aws configure:

import boto3
s3 = boto3.resource('s3')

bucket = s3.Bucket('name')
for obj in bucket.objects.all():
    print(obj.key)

AWS CLI를 사용하면 S3 버킷의 모든 파일을 빠르게 볼 수 있으며 다른 작업도 수행 할 수 있습니다.

AWS CLI를 사용하려면 다음 단계를 따르십시오.

  1. AWS CLI를 설치하십시오 .
  2. 기본 보안 자격 증명 및 기본 AWS 리전을 사용하도록 AWS CLI를 구성하십시오 .
  3. S3 버킷의 모든 파일을 보려면 명령을 사용하십시오.

    AWS s3 ls s3 : // your_bucket_name-재귀

다양한 AWS 서비스에 AWS cli 사용에 대한 참조 : https://docs.aws.amazon.com/cli/latest/reference/


Code in python using the awesome "boto" lib. The code returns a list of files in a bucket and also handles exceptions for missing buckets.

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() ]

Don't forget to replace the < PLACE_HOLDERS > with your values.


The below command will get all the file names from your AWS S3 bucket and write into text file in your current directory:

aws s3 ls s3://Bucketdirectory/Subdirectory/ | cat >> FileNames.txt

You can use standard s3 api -

aws s3 ls s3://root/folder1/folder2/

You can list all the files, in the aws s3 bucket using the command

aws s3 ls path/to/file

and to save it in a file, use

aws s3 ls path/to/file >> save_result.txt

if you want to append your result in a file otherwise:

aws s3 ls path/to/file > save_result.txt

if you want to clear what was written before.

It will work both in windows and Linux.


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;
}

Alternatively you can use Minio Client aka mc. Its Open Source and compatible with AWS S3. It is available for Linux, Windows, Mac, FreeBSD.

All you have do do is to run mc ls command for listing the contents.

$ 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

Note:

  • s3: Alias for Amazon S3
  • kline: AWS S3 bucket name

Installing Minio Client Linux Download mc for:

$ chmod 755 mc
$ ./mc --help

Setting up AWS credentials with Minio Client

$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12

Note: Please replace mys3 with alias you would like for this account and ,BKIKJAA5BMMU2RHO6IBB, V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 with your AWS ACCESS-KEY and SECRET-KEY

Hope it helps.

Disclaimer: I work for Minio


# 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}'

In javascript you can use

s3.listObjects(params, function (err, result) {});

to get all objects inside bucket. you have to pass bucket name inside params (Bucket: name).


Simplified and updated version of the Scala answer by Paolo:

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))
}

Stripping out the generics and using the ListObjectRequest generated by the SDK builders.


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

}

In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call

$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
    echo $obj['Key'];
}

You can redirect output of the above code in to a file to get list of keys.


Use plumbum to wrap the cli and you will have a clear syntax:

import plumbum as pb
folders = pb.local['aws']('s3', 'ls')

The EASIEST way to get a very usable text file is to download S3 Browser http://s3browser.com/ and use the Web URLs Generator to produce a list of complete link paths. It is very handy and involves about 3 clicks.

-Browse to Folder
-Select All
-Generate Urls

Best of luck to you.

참고URL : https://stackoverflow.com/questions/3337912/quick-way-to-list-all-files-in-amazon-s3-bucket

반응형