[2021.07.21~22] 인턴 +142 How to upload multiple files from local PC to AWS S3 using python(boto3)?
해당 게시글은, 로컬 PC 에서 AWS S3에 파일 업로드 하는 방법을 알려주도록 하겠다. (3시간 정도 소요)
S3 — Boto3 Docs 1.18.3 documentation
A dictionary with two elements: url and fields. Url is the url to post to. Fields is a dictionary filled with the form fields and respective values to use when submitting the post. For example: {'url': 'https://mybucket.s3.amazonaws.com 'fields': {'acl': '
boto3.amazonaws.com
-> AWS S3 BOTO3 document 이다.
1. AWSCLI64PY3 을 로컬 PC로 부터 설치 한다.
https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/install-windows.html
Windows에서 AWS CLI 버전 1 설치, 업데이트 및 제거 - AWS Command Line Interface
이 페이지에 작업이 필요하다는 점을 알려 주셔서 감사합니다. 실망시켜 드려 죄송합니다. 잠깐 시간을 내어 설명서를 향상시킬 수 있는 방법에 대해 말씀해 주십시오.
docs.aws.amazon.com
2. 명령 프롬포트로 AWS CLI Version1 설치 및 업데이트
pip3 install awscli --upgrade --user
C:\Users\injekim97>pip3 install awscli --upgrade --user
Collecting awscli
Using cached awscli-1.20.3.tar.gz (1.5 MB)
Requirement already satisfied: botocore==1.21.3 in c:\users\injekim97\anaconda3\lib\site-packages (from awscli) (1.21.3)
Collecting docutils<0.16,>=0.10
Using cached docutils-0.15.2-py3-none-any.whl (547 kB)
Requirement already satisfied: s3transfer<0.6.0,>=0.5.0 in c:\users\injekim97\anaconda3\lib\site-packages (from awscli) (0.5.0)
Requirement already satisfied: PyYAML<5.5,>=3.10 in c:\users\injekim97\anaconda3\lib\site-packages (from awscli) (5.4.1)
Collecting colorama<0.4.4,>=0.2.5
Using cached colorama-0.4.3-py2.py3-none-any.whl (15 kB)
Collecting rsa<4.8,>=3.1.2
Using cached rsa-4.7.2-py3-none-any.whl (34 kB)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in c:\users\injekim97\anaconda3\lib\site-packages (from botocore==1.21.3->awscli) (2.8.1)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in c:\users\injekim97\anaconda3\lib\site-packages (from botocore==1.21.3->awscli) (0.10.0)
Requirement already satisfied: urllib3<1.27,>=1.25.4 in c:\users\injekim97\anaconda3\lib\site-packages (from botocore==1.21.3->awscli) (1.26.4)
Requirement already satisfied: six>=1.5 in c:\users\injekim97\anaconda3\lib\site-packages (from python-dateutil<3.0.0,>=2.1->botocore==1.21.3->awscli) (1.15.0)
Collecting pyasn1>=0.1.3
Using cached pyasn1-0.4.8-py2.py3-none-any.whl (77 kB)
Building wheels for collected packages: awscli
Building wheel for awscli (setup.py) ... done
Created wheel for awscli: filename=awscli-1.20.3-py3-none-any.whl size=3627111 sha256=6fb936aa0a5c8fd1e013770da863cfe7b7ca83da1f85bf6e00703368c3b6d612
Stored in directory: c:\users\injekim97\appdata\local\pip\cache\wheels\30\e7\11\0e92171806d7108ac845849b691c13bb6fb9df8382729eb620
Successfully built awscli
Installing collected packages: pyasn1, rsa, docutils, colorama, awscli
WARNING: The scripts pyrsa-decrypt.exe, pyrsa-encrypt.exe, pyrsa-keygen.exe, pyrsa-priv2pub.exe, pyrsa-sign.exe and pyrsa-verify.exe are installed in 'C:\Users\injekim97\AppData\Roaming\Python\Python38\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
pylint 2.7.4 requires astroid<2.7,>=2.5.2, but you have astroid 2.5 which is incompatible.
Successfully installed awscli-1.20.3 colorama-0.4.3 docutils-0.15.2 pyasn1-0.4.8 rsa-4.7.2
-> 위의 명령어를 통해 설치된 내용이다.
그런 다음에, 명령프롬포트에서 where명령을 사용하여 aws파일 위치(경로)를 찾는다 .
where aws
C:\Program Files\Amazon\AWSCLI\bin\aws.exe (이것은 window에서 aws cli가 깔린 경로임)
3. 환경변수 설정(로컬 PC)
윈도우 -> 환경변수 입력 -> 환경변수 클릭
환경 변수에 where aws 한 것을 그대로 복사해서 추가
C:\Program Files\Amazon\AWSCLI\bin\aws.exe
4. 명령프롬포트(로컬 PC)에서 aws cli list check
C:\Users\injekim97> aws configure list
Name Value Type Location
---- ----- ---- --------
profile <not set> None None
access_key <not set> None None
secret_key <not set> None None
region <not set> None None
-> aws configure list을 통해, 로컬 PC 에서 자격 증명이 설정 되었는지 확인할 수 있다.
자격 증명 설정을 안하고, S3 업로드 시 아래와 같은 에러 발생
NoCredentialsError: Unable to locate credentials
5. 명령프롬포트에서 자격 증명 설정 하기(aws cli => access_key,secret_key,region)
C:\Users\injekim97>aws configure
AWS Access Key ID [None]: AKIAV4FRRCI65BXBR647
AWS Secret Access Key [None]: 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
Default region name [None]: ap-northeast-2
Default output format [None]: json
-> 해당 key 들은, 자격증명 발급했을 때, 그 키 값들을 복사하여 붙여주면 됨.
그런 다음에, aws list를 출력해보면, 제대로 값이 설정 되었을 것이다.
C:\Users\injekim97>aws configure list
Name Value Type Location
---- ----- ---- --------
profile <not set> None None
access_key ****************R647 shared-credentials-file
secret_key ****************1qhQ shared-credentials-file
region ap-northeast-2 config-file ~/.aws/config
---------------------------------------------------------------------------------------------------------------
자, 이제 boto3를 이용하여, 로컬PC 에서 aws s3로 파일을 업로드 해보자
<소스 코드>
import os
import boto3
def file_upload_s3():
s3_bucket = "elk-data-storage"
s3 = boto3.resource('s3')
dir_path = [] # dir_path 은 local PC에 업로드 할 경로를 저장하기 위함 용도
file_name = [] # file_name 은 업로드 할 경로에 파일 이름을 저장하기 위한 용도
directory_path = "C:\\Users\\injekim97\\Desktop\\IAM_USER_ELK" # ★★★★★ 업로드 할 파일 경로를 지정 ★★★★★
for file in os.listdir(directory_path):
path = os.path.join(directory_path,file) # C:\Users\injekim97\Desktop\IAM_USER_ELK+ {파일 이름} 식으로 붙어짐
dir_path.append(path)
file_name.append(file)
# ★★★★★ range는 업로드 할 파일에 수에 따라 range(수)를 부여함 ★★★★★
# e.g : 5개면 5를 부여해야함 0~4 총 5개
# ★★★★★ 일부로 try , except 문을 사용해서 총 999개의 해당 경로의 파일을 업로드 하게끔 함. ★★★★★
try :
for i in range(999):
s3.meta.client.upload_file(dir_path[i], s3_bucket,file_name[i])
except :
pass
print("Local PC -> AWS S3 파일 업로드를 완료하였습니다.")
file_upload_s3()
* s3.meta.client.upload_file(r'경로',S3버킷이름,'S3에 저장할 파일 이름')
* ★★★★★ directory_path = "C:\\Users\\injekim97\\Desktop\\IAM_USER_ELK"
(경로를 복붙하게 되면 \ 가 되는데 꼭 \\로 써야 작동됨) ★★★★★
-> \ 하나만 쓰면 unicode 에러 발생함
----------------------------------------------------------------------------------------------------------------------
<출력 결과>
-> 07.22 디렉토리에 있는 모든 경로의 파일들을 업로드 하였다.
-> 다른 폴더로 했을 때도 성공.
댓글