【问题标题】:Upload files to s3 bucket using python gives Access Denied使用 python 将文件上传到 s3 存储桶会导致访问被拒绝
【发布时间】:2020-10-09 01:55:46
【问题描述】:

我创建了一个 Python 脚本,它应该将文件从我的本地 ec2 上传到 s3 存储桶

import boto3

s3 = boto3.resource('s3')
data = open('backupFile.txt', 'rb')
s3.Bucket('mlsd').put_object(Key='backupFile.txt', Body=data)

我访问了 AWS 账户详细信息并获得了凭证。

我执行了aws configure 在我的 EC2 上设置凭据。

听到的是使用aws configure list 的凭据输出:

我去了.aws/credentials并粘贴了access_key_idsecret_access_keytoken

我确保令牌没有过期。

当我运行脚本时,我得到了以下输出:

不确定是什么问题。

【问题讨论】:

  • 您用于连接存储桶的 IAM 角色的权限是什么?
  • 在哪里可以设置,应该在上面配置什么?
  • 您在 .aws 文件夹中使用了一些凭据。他们来自哪里?如果您撰写有关令牌及其到期的文章,则意味着您正在使用某些 IAM 角色。我不知道你是从哪里得到这个角色的。因此我的问题。
  • 我没有设置任何角色。登录后我从帐户详细信息中获得了凭据。

标签: amazon-web-services python-2.7 amazon-s3 amazon-ec2 boto3


【解决方案1】:

Boto3 在可能的位置检测到您的凭据,如 here 所述,因此它应该找到您的 access_key_id 和 secret_access_key

确保您使用其 access_key_id 的用户有权访问 S3 存储桶。

我尝试了这个代码示例并且它有效:

import logging
import boto3
from botocore.exceptions import ClientError

def upload_file(file_name, bucket, object_name=None):
   """Upload a file to an S3 bucket

   :param file_name: File to upload
   :param bucket: Bucket to upload to
   :param object_name: S3 object name. If not specified then file_name is used
   :return: True if file was uploaded, else False
   """

   # If S3 object_name was not specified, use file_name
   if object_name is None:
       object_name = file_name

   # Upload the file
   s3_client = boto3.client('s3')
   try:
       response = s3_client.upload_file(file_name, bucket, object_name)
   except ClientError as e:
       logging.error(e)
       return False
   return True

【讨论】:

  • 你确定语法吗?我收到 SyntaxError: 'return' outside function
  • 是的,有一个错误。因为 Python 不使用大括号缩进,所以空格很关键。因此,函数内部的 return 语句与外部提及 return 语句时不同。我修好了。
猜你喜欢
  • 2019-12-04
  • 2021-07-05
  • 2019-02-03
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 2018-05-21
  • 2018-01-10
  • 1970-01-01
相关资源
最近更新 更多