简体   繁体   English

使用 boto3 (python) 将文件从 s3 下载到本地机器

[英]Downloading a file from s3 to local machine using boto3 (python)

I'm trying to use a python script to automate downloading a file from AWS s3 to my local machine.我正在尝试使用 python 脚本自动将文件从 AWS s3 下载到我的本地机器。 The python script itself is hosted on ubuntu (AWS ec2 instance), so it's not recognizing a directory on my local machine. python 脚本本身托管在 ubuntu(AWS ec2 实例)上,因此它无法识别我本地机器上的目录。

Here's my code:这是我的代码:

import os
import boto3
from boto3.session import Session
print("this script downloads the file from s3 to local machine")

s3 = boto3.resource('s3')

BUCKET_NAME = 'sfbucket.myBucket'
KEY = 'sf_events.json'

s3.Bucket(BUCKET_NAME).download_file(KEY, '/Users/Documents/my_file.json')

print('end')

However, this gives me the following error:但是,这给了我以下错误:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/Documents/my_file.json.CDC5FEf4'

Can anyone tell me what I'm doing wrong?谁能告诉我我做错了什么? If I replace the output directory to /home/ubuntu/ it works fine, but I want the file on my local machine.如果我将输出目录替换为/home/ubuntu/它工作正常,但我想要我的本地机器上的文件。 Thanks in advance.提前致谢。

The script has to run on your local Windows machine not on EC2 instance.该脚本必须在您的本地 Windows 机器上运行,而不是在 EC2 实例上运行。

Alternatively, you can simply use aws cli或者,您可以简单地使用 aws cli

aws s3 cp s3://sfbucket.myBucket/sf_events.json /Users/Documents/my_file.json

As you are trying to download the file using the EC2 instance, this machine doesn't know your local path /Users/Documents/my_file.json当您尝试使用 EC2 实例下载文件时,此计算机不知道您的本地路径/Users/Documents/my_file.json

You have two options:您有两个选择:

  1. Run this script directly in your local machine.直接在本地机器上运行此脚本。 In this case, you have to run this script in your local machine and make sure you have access to this bucket.在这种情况下,您必须在本地计算机上运行此脚本并确保您有权访问此存储桶。

  2. Run this script in EC2 Instance and copy.在 EC2 实例中运行此脚本并复制。 In this case, you have to download the file to somewhere /home/ubuntu/ and then after in your local machine make a copy from EC2.在这种情况下,您必须将文件下载到某个地方/home/ubuntu/然后在您的本地机器上从 EC2 复制一份。 You can use [SCP][1]你可以使用[SCP][1]

You can install the SCP server in your local machine but the problem is that your local machine probably doesn't have a private IP, so every time that your local IP change you have to update the script.您可以在本地机器上安装 SCP 服务器,但问题是您的本地机器可能没有私有 IP,因此每次您的本地 IP 更改时,您都必须更新脚本。 Maybe you should think about to do whatever you need to do with this file directly on EC2 Instance or if it's a real manual thing, sending via email, maybe?也许您应该考虑直接在 EC2 实例上对这个文件做任何您需要做的事情,或者如果它是一个真正的手动操作,也许可以通过电子邮件发送?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM