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

1、建立终端节点python

    为何要建立终端节点,把VPC和S3管理起来呢?若是不将VPC和S3经过终端节点管理起来,那么VPC中EC2实例访问S3存储桶是经过公共网络的;一旦关联起来,那么VPC中EC2实例访问S3存储桶走的就是内部网络。好处有两个:1. 走内部网络就不会产生流量费用;2. 走内部网络速度快,不会由于网络缘由致使咱们的Python脚本产生异常。
安全

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

image.png

image.png


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

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

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

    3. 配置环境变量
命令行

    image.png

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

    image.png


3、生成AWS IAM用户密钥并配置生命周期

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

    image.png

    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


3、编辑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)


4、测试并安排定时任务

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

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

    image.png


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

    对于上传到S3存储桶中的文件,咱们想按期删除30天之前的文件,咱们能够设置存储桶的生命周期,自动删除过时文件。

image.png

添加生命周期规则

image.png

image.png

image.png

相关文章
相关标签/搜索