oss迁移

阿里云oss跨区域迁移

由于阿里云跨区域复制需收流量费,而且不支持过滤已存在文件,所以利用api实现过滤掉已存在的文件,上传使用内网,降低流量费用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# -*- coding: utf-8 -*-

import os
import time
import oss2
import logging

# 打印log
logging.basicConfig(filename=os.path.join(os.getcwd(),'ossdebug.log'),level=logging.DEBUG)
auth = oss2.Auth('<阿里云access id>', '<阿里云access key>')
bucket = oss2.Bucket(auth, '<目标endpoint>', '<目标bucket>')
bucket2 = oss2.Bucket(auth, '<源endpoint>', '<源bucket>')

logging.info("开始时间:"+ time.asctime( time.localtime(time.time()) ))

for b in oss2.ObjectIterator(bucket2): ## 罗列文件
a = b.key
existfile = bucket.object_exists(a) ## 判断目标bucket是否存在文件
if existfile:
logging.info(a)
else:
f = a.split('/', 1)[-1] ## 去除文件夹,取文件名
print(f)
bucket2.get_object_to_file(a,f) ## 下载差异文件
bucket.put_object_from_file(a,f) ## 上传差异文件
if os.path.exists(f): ## 删除本地差异文件
os.remove(f)

logging.info("结束时间:" + time.asctime( time.localtime(time.time()) ))