2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonでS3にアクセスできるか簡単に確かめる

Last updated at Posted at 2021-12-08

Python環境上で接続を確かめる方法

主に、バケットに接続できる権限なのかを調べるときに使えるかと

実行はpython cli上にコピペすればOK!!

実行コマンド

import boto3
s3 = boto3.resource('s3', aws_access_key_id='ACCESS_KEY', aws_secret_access_key='SECRET_KEY')
bucket = s3.Bucket('BUCKET_NAME')
for obj in bucket.objects.all():
    print(obj.key)

これを実行して、バケットに格納されているファイルとディレクトリが表示されたら成功!

実行例

成功

アクセスキーやバケット名はマスキングしてあります

>>> import boto3
>>> s3 = boto3.resource('s3', aws_access_key_id='*******', aws_secret_access_key='********')
ket = s3.Bucket('********')
for obj in bucket.o>>> bucket = s3.Bucket('********')
>>> for obj in bucket.objects.all():
...     print(obj.key)
... 
a.txt
t/
t/b.txt

失敗

アクセスキー や シークレットキーが間違えていると、以下の様にエラーが出力される

>>> import boto3
>>> s3 = boto3.resource('s3', aws_access_key_id='ACCESS_KEY', aws_secret_access_key='SECRET_KEY')
n bucket.objects.all():
    print(obj.key)

>>> bucket = s3.Bucket('BUCKET_NAME')
>>> for obj in bucket.objects.all():
...     print(obj.key)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/site-packages/boto3/resources/collection.py", line 83, in __iter__
    for page in self.pages():
  File "/usr/local/lib/python3.8/site-packages/boto3/resources/collection.py", line 166, in pages
    for page in pages:
  File "/usr/local/lib/python3.8/site-packages/botocore/paginate.py", line 255, in __iter__
    response = self._make_request(current_kwargs)
  File "/usr/local/lib/python3.8/site-packages/botocore/paginate.py", line 332, in _make_request
    return self._method(**current_kwargs)
  File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 276, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.8/site-packages/botocore/client.py", line 586, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you provided does not exist in our records.
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?