您的位置:首页 > 编程语言 > Python开发

使用Python boto3上传Windows EC2实例中的文件至S3存储桶中

2018-07-17 22:18 661 查看

一、创建终端节点

    为什么要创建终端节点,把VPC和S3管理起来呢?如果不将VPC和S3通过终端节点管理起来,那么VPC中EC2实例访问S3存储桶是通过公共网络的;一旦关联起来,那么VPC中EC2实例访问S3存储桶走的就是内部网络。好处有两个:1. 走内部网络就不会产生流量费用;2. 走内部网络速度快,不会因为网络原因导致我们的Python脚本产生异常。

VPC->终端节点->创建终端节点->将VPC和S3关联->关联子网


二、在Windows中安装Python3编译器以及boto3库

    1. 下载地址:https://www.python.org/

    2. 双击安装,默认安装路径“C:\Users\用户\AppData\Local\Programs\Python\Python36”

    3. 配置环境变量

    

    4. 安装boto3开发库(环境变量配好即可使用pip命令)

    


三、生成AWS IAM用户密钥并配置

    1. IAM->用户->选择具有访问S3权限的用户->安全证书->创建访问安全密钥->下载密钥文件到本地

    

    2. 在Windows实例上配置AWS密钥认证

a) 创建~/.aws/credentials 文件,文件内容如下:
[default]
aws_access_key_id = xxxxxx
aws_secret_access_key = xxxxxx

b) 创建~/.aws/config 文件,文件内容如下:
[default]
region=cn-north-1


三、编辑Python3脚本,脚本名为“s3_upload.py”

import os
import datetime
import boto3
import logging
from boto3.s3.transfer import TransferConfig

logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='E:\\xxx\\xxx\\xxx\\aws_upload.log',
                filemode='a')

delta = datetime.timedelta(days=2)
now = datetime.datetime.now()
s3 = boto3.client('s3')
bucket_name = 'daily-backup'
file_dir='E:\\xxx\\xxx\\xxx'
GB = 1024 ** 3
# 单个文件大于10GB,需要设置此值
config = TransferConfig(multipart_threshold=5 * GB)

os.chdir(file_dir)

file_list = os.listdir()

for file in file_list:
    # 只上传zip文件
    if file.endswith('.zip'):
        # 上传两天前生成的文件
        ctime = datetime.datetime.fromtimestamp(os.path.getctime(file))
        if ctime < (now-delta):
            try:
                s3.upload_file(file, bucket_name, file, Config=config)
            except Exception as e:
                logging.error(e)
                logging.error("%s upload failed." % file)
            else:
                # 上传成功则删除本地文件
                logging.info("%s upload successful." % file)
                os.remove(file)


四、测试并安排定时任务

    1. 在Windows CMD命令行中手动运行刚刚编辑的python脚本

    2. 如果成功,则编辑Windows定时任务,每天定时上传本地目录下的文件至S3存储桶中

    


五、设置S3存储桶生命周期

    对于上传到S3存储桶中的文件,我们想定期删除30天以前的文件,我们可以设置存储桶的生命周期,自动删除过期文件。

添加生命周期规则

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  s3 python boto3