目录
python 上传本地文件到阿里云的oss
背景
清理es日志,对生产环境的数据做了导出压缩,上传到阿里云的oss的某个bucket下
脚本
#!/usr/bin/env
import oss2
import os
import fnmatch
#这里不知道怎么创建或者获取的,可以去看go专栏,文件中转站部分 https://www.cnblogs.com/liwenchao1995/p/16488800.html#112-寻找现成工具
access_key_id = 'access_id'
access_key_secret = 'access_secret'
# 填写自己的 Bucket 名称和上传地址
bucket_name = 'dev-base'
upload_path = 'prod-elasticsearch-backup-2022/'
work_path = './' # 将路径替换为实际的目录路径
# 创建 OSS 链接
auth = oss2.Auth(access_key_id, access_key_secret)
#这里的注意,我这里瞎写的,需要在阿里云控制台的概述里看自己的公网地址填写
bucket = oss2.Bucket(auth, 'http://oss-cn-jinan.aliyuncs.com', bucket_name)
# 上传文件到 OSS
def oss_upload_file(file_path):
# 构造上传路径
file_name = os.path.basename(file_path)
oss_path = upload_path + file_name
# 上传文件
with open(file_path, 'rb') as file_obj:
result = bucket.put_object(oss_path, file_obj)
print(file_name,"upload success")
# 测试
#file_path = 'aaa.go'
#oss_url = oss_upload_file(file_path)
def upload_file(work_path):
for root, dirs, files in os.walk(work_path):
# 使用 fnmatch 进行模式匹配,筛选出 zip 结尾的文件
for file in files:
if fnmatch.fnmatch(file, '*.zip'):
# 打印文件绝对路径
#print(os.path.join(root, file))
#print(file)
oss_upload_file(file)
upload_file(work_path)