Development Tip

전체 S3 버킷을 다운로드 하시겠습니까?

yourdevel 2020. 10. 2. 23:26
반응형

전체 S3 버킷을 다운로드 하시겠습니까?


AWS Management Console에서 전체 S3 버킷을 다운로드하는 옵션이없는 것 같습니다.

내 버킷 중 하나에있는 모든 것을 쉽게 잡을 수있는 방법이 있습니까? 나는 루트 폴더를 공개 wget하고 모든 것을 잡는 데 사용 하고 다시 비공개로 만드는 것에 대해 생각하고 있었지만 더 쉬운 방법이 있는지 모르겠습니다.


AWS CLI

AWS CLI에 대한 설명서

AWS는 최근에 명령 줄 도구를 출시했습니다. 이것은 boto와 매우 유사하게 작동하며 sudo easy_install awscli또는 사용하여 설치할 수 있습니다.sudo pip install awscli

설치가 완료되면 다음을 간단히 실행할 수 있습니다.

명령 :

aws s3 sync s3://<source_bucket> <local_destination>

예를 들면

aws s3 sync s3://mybucket .

모든 개체를 mybucket현재 디렉터리로 다운로드합니다 .

출력 :

download: s3://mybucket/test.txt to test.txt
download: s3://mybucket/test2.txt to test2.txt

이렇게하면 모든 파일이 다운로드됩니다 (단방향 동기화). 그것은 것입니다 하지 현재 디렉토리에있는 기존 파일을 (당신이하지 않으면 삭제 --delete 지정 ), 그리고 S3에 파일을 변경하거나 삭제하지 않습니다.

S3 버킷에서 S3 버킷으로 또는 로컬에서 S3 버킷으로 동기화 할 수도 있습니다.

문서 및 기타 예를 확인하십시오.

http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

버킷에서 폴더 다운로드

위의 예는 전체 버킷을 다운로드하는 방법이지만 다음을 수행하여 폴더를 재귀 적으로 다운로드 할 수도 있습니다.

aws s3 cp s3://BUCKETNAME/PATH/TO/FOLDER LocalFolderName --recursive

이렇게하면 CLI가 버킷 PATH/TO/FOLDER내의 디렉터리 내에서 모든 파일과 폴더 키를 반복적으로 다운로드하도록 지시합니다 BUCKETNAME.


s3cmd사용 하여 버킷을 다운로드 할 수 있습니다 .

s3cmd --configure
s3cmd sync s3://bucketnamehere/folder /destination/folder

최신 정보

Rclone 이라는 또 다른 도구를 사용할 수 있습니다 . 다음은 Rclone 문서의 코드 샘플입니다.

rclone sync /home/local/directory remote:bucket

s3cmd를 포함하여 Amazon S3 데이터를 로컬 머신에 복사하는 데 몇 가지 다른 방법을 사용했으며 가장 쉬운 방법은 Cyberduck 입니다. Amazon 자격 증명을 입력하고 간단한 인터페이스를 사용하여 버킷 / 폴더 / 파일을 다운로드 / 업로드 / 동기화하기 만하면됩니다.

스크린 샷


기본적으로이를 수행 할 수있는 많은 옵션이 있지만 가장 좋은 방법은 AWS CLI를 사용하는 것입니다.

여기에 연습이 있습니다.

  • 1 단계

머신에 AWS CLI 다운로드 및 설치

MSI 설치 프로그램을 사용하여 AWS CLI 설치 (Windows)

번들 설치 프로그램 (Linux, OS X 또는 Unix)을 사용하여 AWS CLI를 설치합니다.

  • 2 단계

AWS CLI 구성

여기에 이미지 설명 입력

계정을 만들 때받은 유효한 액세스 키비밀 키 를 입력했는지 확인하십시오.

  • 3 단계

다음 명령으로 s3 버킷 동기화

aws s3 sync s3://yourbucket /local/path

위의 명령을 다음 데이터로 교체

yourbucket >> 다운로드하려는 s3 버킷

/ local / path >> 모든 파일을 다운로드 할 로컬 시스템의 경로

도움이 되었기를 바랍니다!


AWS S3 CLI를 사용하여 다운로드하려면 :

aws s3 cp s3://WholeBucket LocalFolder --recursive
aws s3 cp s3://Bucket/Folder LocalFolder --recursive

코드를 사용하여 다운로드하려면 AWS SDK를 사용하십시오 .

GUI를 사용하여 다운로드하려면 Cyberduck을 사용하십시오 .

그것이 도움이되기를 바랍니다 .. :)


S3 브라우저는 제가 찾은 가장 쉬운 방법입니다. 그것은 우수한 소프트웨어입니다 ... 그리고 비 상업적 사용을 위해 무료입니다. Windows에만 해당됩니다.

http://s3browser.com/


Visual Studio를 사용하는 경우 http://aws.amazon.com/visualstudio/를 다운로드합니다.

설치 후 Visual Studio-AWS Explorer-S3-Your bucket-Double click으로 이동합니다.

창에서 모든 파일을 선택할 수 있습니다. 마우스 오른쪽 버튼을 클릭하고 파일을 다운로드합니다.


일부 osx 사용자에게 도움이 될 수있는 또 다른 옵션 전송 입니다. s3 파일에 연결할 수도있는 ftp 프로그램입니다. 그리고 ftp 또는 s3 스토리지를 파인더의 폴더마운트 하는 옵션이 있습니다 . 그러나 제한된 시간 동안입니다.


s3에 대해 약간의 개발을 수행했지만 전체 버킷을 다운로드하는 간단한 방법을 찾지 못했습니다. Java로 코딩하려는 경우 jets3t lib를 사용하여 버킷 목록을 만들고 해당 목록을 반복하여 다운로드 할 수 있습니다.

http://jets3t.s3.amazonaws.com/downloads.html

먼저 S3service 객체를 생성 할 수 있도록 AWS Management Consule에서 퍼블릭 프라이빗 키 세트를 가져옵니다.

AWSCredentials awsCredentials = new AWSCredentials(YourAccessKey, YourAwsSecretKey);
s3Service = new RestS3Service(awsCredentials);

그런 다음 버킷 객체의 배열을 가져옵니다.

S3Object[] objects = s3Service.listObjects(YourBucketNameString);

마지막으로이 코드를 사용하여 한 번에 하나씩 객체를 다운로드하기 위해 해당 배열을 반복합니다.

S3Object obj = s3Service.getObject(bucket, fileName);
            file = obj.getDataInputStream();

스레드 세이프 싱글 톤에 연결 코드를 넣었습니다. 명백한 이유로 필요한 try / catch 구문이 생략되었습니다.

Python으로 코딩하고 싶다면 Boto를 대신 사용할 수 있습니다.

추신은 BucketExplorer를 둘러 본 후 내 원하는 것을합니다. https://forums.aws.amazon.com/thread.jspa?messageID=248429


AWS CLI 와 함께이 명령을 사용합니다 .

aws s3 cp s3://bucketname. --recursive

@Layke의 답변은 좋지만 데이터가 많고 영원히 기다리지 않으려 는 경우 AWS S3 CLI sync 명령을 통해 대규모 병렬화로 버킷을 동기화하는 방법대한 이 설명서를주의 깊게 살펴 봐야합니다 . 다음 명령은 AWS CLI에 1,000 개의 스레드를 사용하여 작업 (각 작은 파일 또는 멀티 파트 복사본의 일부)을 실행하고 100,000 개의 작업을 미리 보도록 지시합니다.

aws configure set default.s3.max_concurrent_requests 1000
aws configure set default.s3.max_queue_size 100000

이를 실행 한 후 다음과 같이 간단한 sync 명령을 사용할 수 있습니다.

aws s3 sync s3://source-bucket/source-path s3://destination-bucket/destination-path

또는

aws s3 sync s3://source-bucket/source-path c:\my\local\data\path

CPU 4 코어 및 16GB RAM이있는 시스템에서 내 경우 (3-50GB 파일)의 경우 동기화 / 복사 속도가 약 9.5MiB / s에서 700 + MiB / s로 기본 구성에 비해 70 배 증가했습니다.


S3Fox와 함께 Firefox를 사용하는 경우 모든 파일을 선택하고 (처음부터 마지막으로 shift-select) 마우스 오른쪽 버튼을 클릭하고 모두 다운로드 할 수 있습니다. 문제없이 500 개 이상의 파일을 사용했습니다.


https://github.com/minio/mc를 사용 하면됩니다 .

mc cp -r https://s3-us-west-2.amazonaws.com/bucketName/ localdir

mc는 세션, 재개 가능한 다운로드, 업로드 등을 지원합니다. mcLinux, OS X 및 Windows 운영 체제를 지원합니다. Golang으로 작성되었으며 Apache 버전 2.0으로 출시되었습니다.


AWS sdk API는 전체 폴더 및 리포지토리를 s3에 업로드하고 s3의 전체 버킷을 로컬로 다운로드하는 데 가장 적합한 옵션 일뿐입니다.

전체 폴더를 s3에 업로드하는 경우

aws s3 sync . s3://BucketName

전체 s3 버킷을 로컬로 다운로드

aws s3 sync s3://BucketName . 

또한 다운로드 할 s3의 특정 폴더에 대해 BucketName / Path와 같은 경로를 할당 할 수 있습니다.


Windows에서 선호하는 GUI 도구는 S3 용 Cloudberry Explorer, http://www.cloudberrylab.com/free-amazon-s3-explorer-cloudfront-IAM.aspx 입니다. 상당히 세련된 파일 탐색기, ftp와 유사한 인터페이스가 있습니다.


거기에 파일 만있는 경우 (하위 디렉터리 없음) 빠른 해결책은 모든 파일 ( click첫 번째, Shift+click마지막) 을 선택하고 Enter또는 right click을 누르고를 선택하는 것 Open입니다. 대부분의 데이터 파일은 컴퓨터로 바로 다운로드됩니다.


다른 GUI 옵션을 추가하기 위해 WinSCP의 S3 기능을 사용 합니다 . 연결이 매우 쉽고 UI에서 액세스 키와 비밀 키만 있으면됩니다. 그런 다음 중첩 된 폴더의 재귀 다운로드를 포함하여 액세스 가능한 버킷에서 필요한 파일을 찾아 다운로드 할 수 있습니다.

보안을 통해 새 소프트웨어를 지우는 것이 어려울 수 있고 WinSCP가 상당히 널리 퍼져 있기 때문에보다 전문화 된 유틸리티를 설치하는 것보다 사용하는 것이 정말 유익 할 수 있습니다.


  1. Windows 사용자는 설치 지침이있는이 링크에서 S3EXPLORER를 다운로드해야합니다.- http ://s3browser.com/download.aspx

  2. 그런 다음 secretkey, accesskey 및 region과 같은 AWS 자격 증명을 s3explorer에 제공합니다.이 링크에는 s3explorer에 대한 구성 지침이 포함되어 있습니다. 브라우저에 붙여 넣기 링크 복사 : s3browser.com/s3browser-first-run.aspx

  3. 이제 모든 s3 버킷이 s3explorer의 왼쪽 패널에 표시됩니다.

  4. 버킷을 선택하고 왼쪽 상단의 버킷 메뉴를 클릭 한 다음 메뉴에서 모든 파일 다운로드 옵션을 선택하십시오. 다음은 동일한 스크린 샷입니다.

버킷 선택 화면

  1. Then browse a folder to download the bucket at a particular place

  2. Click on OK and your download would begin.


aws sync is the perfect solution. It does not do a two way.. it is a one way from source to destination. Also, if you have lots of items in bucket it will be a good idea to create s3 endpoint first so that download happens faster (because download does not happen via internet but via intranet) and no charges


Here is some stuff to download all buckets, list them, list their contents.

    //connection string
    private static void dBConnection() {
    app.setAwsCredentials(CONST.getAccessKey(), CONST.getSecretKey());
    conn = new AmazonS3Client(app.getAwsCredentials());
    app.setListOfBuckets(conn.listBuckets());
    System.out.println(CONST.getConnectionSuccessfullMessage());
    }

    private static void downloadBucket() {

    do {
        for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
            app.setBucketKey(objectSummary.getKey());
            app.setBucketName(objectSummary.getBucketName());
            if(objectSummary.getKey().contains(CONST.getDesiredKey())){
                //DOWNLOAD
                try 
                {
                    s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
                    s3Client.getObject(
                            new GetObjectRequest(app.getBucketName(),app.getBucketKey()),
                            new File(app.getDownloadedBucket())
                            );
                } catch (IOException e) {
                    e.printStackTrace();
                }

                do
                {
                     if(app.getBackUpExist() == true){
                        System.out.println("Converting back up file");
                        app.setCurrentPacsId(objectSummary.getKey());
                        passIn = app.getDataBaseFile();
                        CONVERT= new DataConversion(passIn);
                        System.out.println(CONST.getFileDownloadedMessage());
                    }
                }
                while(app.getObjectExist()==true);

                if(app.getObjectExist()== false)
                {
                    app.setNoObjectFound(true);
                }
            }
        }
        app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
    } 
    while (app.getS3Object().isTruncated());
}

/----------------------------Extension Methods-------------------------------------/

//Unzip bucket after download 
public static void unzipBucket() throws IOException {
    unzip = new UnZipBuckets();
    unzip.unZipIt(app.getDownloadedBucket());
    System.out.println(CONST.getFileUnzippedMessage());
}

//list all S3 buckets
public static void listAllBuckets(){
    for (Bucket bucket : app.getListOfBuckets()) {
        String bucketName = bucket.getName();
        System.out.println(bucketName + "\t" + StringUtils.fromDate(bucket.getCreationDate()));
    }
}

//Get the contents from the auto back up bucket
public static void listAllBucketContents(){     
    do {
        for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
            if(objectSummary.getKey().contains(CONST.getDesiredKey())){
                System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
                app.setBackUpCount(app.getBackUpCount() + 1);   
            }
        }
        app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
    } 
    while (app.getS3Object().isTruncated());
    System.out.println("There are a total of : " + app.getBackUpCount() + " buckets.");
}

}


You may simple get it with s3cmd command:

s3cmd get --recursive --continue s3://test-bucket local-directory/

As Neel Bhaat has explained in this blog, there are many different tools that can be used for this purpose. Some are AWS provided, where most are third party tools. All these tools require you to save your AWS account key and secret in the tool itself. Be very cautious when using third party tools, as the credentials you save in might cost you, your entire worth and drop you dead.

Therefore, I always recommend using the AWS CLI for this purpose. You can simply install this from this link. Next, run the following command and save your key, secret values in AWS CLI.

aws configure

And use the following command to sync your AWS S3 Bucket to your local machine. (The local machine should have AWS CLI installed)

aws s3 sync <source> <destination>

Examples:

1) For AWS S3 to Local Storage

aws s3 sync <S3Uri> <LocalPath>

2) From Local Storage to AWS S3

aws s3 sync <LocalPath> <S3Uri>

3) From AWS s3 bucket to another bucket

aws s3 sync <S3Uri> <S3Uri> 

If you only want to download the bucket from AWS, first install the AWS CLI in your machine. In terminal change the directory to where you want to download the files and run this command.

aws s3 sync s3://bucket-name .

If you also want to sync the both local and s3 directories (in case you added some files in local folder), run this command:

aws s3 sync . s3://bucket-name

My comment doesn't really add a new solution. As many people here said, aws s3 sync is the best. But nobody pointed out a powerful option: dryrun. This option allows you to see what would be downloaded/uploaded from/to s3 when you are using sync. This is really helpful when you don't want to overwrite content either in your local or in a s3 bucket. This is how is used:

aws s3 sync <source> <destination> --dryrun

I used it all the time before pushing new content to a bucket in order to not upload undesired changes.


As @layke said, it is the best practice to download the file from the S3 cli it is a safe and secure. But in some cases, people need to use wget to download the file and here is the solution

aws s3 presign s3://<your_bucket_name/>

This will presign will get you temporary public URL which you can use to download content from S3 using the presign_url, in your case using wget or any other download client.


Try this command:

aws s3 sync yourBucketnameDirectory yourLocalDirectory

For example, if your bucket name is myBucket and local directory is c:\local, then:

aws s3 sync s3://myBucket c:\local

For more informations about awscli check this aws cli installation


AWS CLI is the best option to download an entire S3 bucket locally.

  1. Install AWS CLI.

  2. Configure AWS CLI for using default security credentials and default AWS Region.

  3. To download the entire S3 bucket use command

    aws s3 sync s3://yourbucketname localpath

Reference to use AWS cli for different AWS services: https://docs.aws.amazon.com/cli/latest/reference/


You can use this AWS cli command to download entire S3 bucket content to local folder

aws s3 sync s3://your-bucket-name "Local Folder Path"

If you see error like this

fatal error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)

--no-verify-ssl (boolean)

By default, the AWS CLI uses SSL when communicating with AWS services. For each SSL connection, the AWS CLI will verify SSL certificates. This option overrides the default behavior of verifying SSL certificates. reference

Use this tag with command --no-verify-ssl

aws s3 sync s3://your-bucket-name "Local Folder Path" --no-verify-ssl

If the bucket is quite big there is a command called s4cmd which makes parallel connections and improves the download time:

To install it on Debian like

apt install s4cmd

If you have pip:

pip install s4cmd

있는 ~/.s3cfg경우 파일 을 읽거나 (install s3cmd및 run이 아닌 경우 s3cmd --configure) --access-key=ACCESS_KEY --secret-key=SECRET_KEY명령에 지정할 수 있습니다 .

CLI는 s3cmd. 귀하의 경우 sync에는 파일을 다시 다운로드하지 않고도 다운로드를 취소하고 다시 시작할 수 있으므로 a를 사용하는 것이 좋습니다.

s4cmd [--access-key=ACCESS_KEY --secret-key=SECRET_KEY] sync s3://<your-bucket> /some/local/dir

많은 양의 데이터 (> 1TB)를 다운로드하면 청구서에 영향을 미칠 수 있으므로주의하십시오. 먼저 비용을 계산하십시오.

참고 URL : https://stackoverflow.com/questions/8659382/downloading-an-entire-s3-bucket

반응형