2012-10-25 4 views

답변

24

은이 (테스트되지 않은) 같은 양동이에있는 모든 파일을 다운로드 할 수 있습니다

from boto.s3.connection import S3Connection 

conn = S3Connection('your-access-key','your-secret-key') 
bucket = conn.get_bucket('bucket') 
for key in bucket.list(): 
    try: 
     res = key.get_contents_to_filename(key.name) 
    except: 
     logging.info(key.name+":"+"FAILED") 

가 S3의 폴더가 키 이름을 작성하고 클라이언트 만 폴더로이 표시됩니다 단순히 또 다른 방법입니다 명심하십시오. @ j0nes에

+3

버킷에 슬래시가있는 경로 (예 : 'foo/bar/1')가있는 경우 먼저 경로에 언급 된'디렉토리 '를 모두 만들어야 작동합니다. – Zags

4
import boto, os 

LOCAL_PATH = 'tmp/' 

AWS_ACCESS_KEY_ID = 'YOUUR_AWS_ACCESS_KEY_ID' 
AWS_SECRET_ACCESS_KEY = 'YOUR_AWS_SECRET_ACCESS_KEY' 
bucket_name = 'your_bucket_name' 

# connect to the bucket 
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) 
bucket = conn.get_bucket(bucket_name) 

# go through the list of files 
bucket_list = bucket.list() 
for l in bucket_list: 
    keyString = str(l.key) 
    d = LOCAL_PATH + keyString 
    try: 
    l.get_contents_to_filename(d) 
    except OSError: 
    # check if dir exists 
    if not os.path.exists(d): 
     os.makedirs(d) # Creates dirs recurcivly 
3
#!/usr/bin/env python 

import boto 
import sys, os 
from boto.s3.key import Key 
from boto.exception import S3ResponseError 


DOWNLOAD_LOCATION_PATH = os.path.expanduser("~") + "/s3-backup/" 
if not os.path.exists(DOWNLOAD_LOCATION_PATH): 
    print ("Making download directory") 
    os.mkdir(DOWNLOAD_LOCATION_PATH) 


def backup_s3_folder(): 
    BUCKET_NAME = "your-bucket-name" 
    AWS_ACCESS_KEY_ID= os.getenv("AWS_KEY_ID") # set your AWS_KEY_ID on your environment path 
    AWS_ACCESS_SECRET_KEY = os.getenv("AWS_ACCESS_KEY") # set your AWS_ACCESS_KEY on your environment path 
    conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_ACCESS_SECRET_KEY) 
    bucket = conn.get_bucket(BUCKET_NAME) 

    #goto through the list of files 
    bucket_list = bucket.list() 

    for l in bucket_list: 
     key_string = str(l.key) 
     s3_path = DOWNLOAD_LOCATION_PATH + key_string 
     try: 
      print ("Current File is ", s3_path) 
      l.get_contents_to_filename(s3_path) 
     except (OSError,S3ResponseError) as e: 
      pass 
      # check if the file has been downloaded locally 
      if not os.path.exists(s3_path): 
       try: 
        os.makedirs(s3_path) 
       except OSError as exc: 
        # let guard againts race conditions 
        import errno 
        if exc.errno != errno.EEXIST: 
         raise 




if __name__ == '__main__': 
    backup_s3_folder() 
1

그냥 추가 디렉토리 생성 부분은

from boto.s3.connection import S3Connection 
import os 

conn = S3Connection('your-access-key','your-secret-key') 
bucket = conn.get_bucket('bucket') 

for key in bucket.list(): 
    print key.name 
    if key.name.endswith('/'): 
     if not os.path.exists('./'+key.name): 
      os.makedirs('./'+key.name) 
    else: 
     res = key.get_contents_to_filename('./'+key.name) 

이 현재 디렉토리에 파일을 다운로드하고 필요한 경우 디렉토리를 만듭니다 언급.

관련 문제