簡介
最近在學習Python,為之龐大的第三方庫感到震撼。今天分享一個Python 自動化腳本,功能是將H5靜態資源上傳到OSS,以方便實現CDN加速,我將其放在Jenkins自動發布中使用。該腳本不是我的原創,是前同事留下的,希望對需要的小伙伴有所幫助。
安裝阿里雲第三方庫
pip install oss2
腳本說明
accesskey,accesspassword,bucketname,ossBucket 需要根據自己賬戶情況作出調整
腳本內容
#!/usr/bin/python # -*- coding:utf8 -*- import os import sys import oss2 # 阿里雲相關的token ossAuth = oss2.Auth('accesskey', 'accesspassword') ossBucket = oss2.Bucket(ossAuth, 'oss-cn-hangzhou.aliyuncs.com', 'bucketname') # 本地需要上傳的文件或者目錄,sys.argv: 實現從程序外部向程序傳遞參數。 pathfile = sys.argv[1] # 判斷是否輸入目標目錄(在oss中的目錄,程序會自動創建),如果沒有輸入目標目錄,則直接上傳文件到oss的根目錄下 if len(sys.argv) == 3: ossDir = sys.argv[2] + "/" else: ossDir = "" ee = [1] ee[0] = 1 # 最后一次上傳到哪個文件,第一次上傳請修改ee[0]=1 ff = '550.jpg' # 定義是目錄 def list(dir): fs = os.listdir(dir) for f in fs: file = dir + "/" + f; print("file is" + ":" + file) if os.path.isdir(file): list(file) else: uploadDir(file) # 上傳帶目錄的文件到OSS def uploadDir(path_filename): print("------------------") print(path_filename) remoteName = ossDir + path_filename.split('//')[1] print("remoteName is" + ":" + remoteName) print('uploading..', path_filename, 'remoteName', remoteName) if (ee[0] == 0 and remoteName == ff): ee[0] = 1 if 1 == ee[0]: result = ossBucket.put_object_from_file(remoteName, path_filename) print('http_status: {0}'.format(result.status)) # 上傳文件到OSS def uploadFile(filename): remoteName = ossDir + os.path.basename(filename) print("remoteName is" + ":" + remoteName) print('uploading..', filename, 'remoteName', remoteName) if (ee[0] == 0 and remoteName == ff): ee[0] = 1 if 1 == ee[0]: result = ossBucket.put_object_from_file(remoteName, filename) print('http_status: {0}'.format(result.status)) ##判斷是文件還是目錄 if os.path.isdir(pathfile): if pathfile.endswith('/'): pass else: pathfile += "/" print("it's a directory") list(pathfile) elif os.path.isfile(pathfile): print("it's a normal file") uploadFile(pathfile) else: print("it's a special file (socket, FIFO, device file)")
執行效果展示
python /etc/ansible/scripts/bxq-online-oss.py $WORKSPACE/dist
參考文檔
- python之sys模塊詳解:https://www.cnblogs.com/cherishry/p/5725184.html
- Aliyun OSS SDK for Python:https://aliyun-oss-python-sdk.readthedocs.io/en/stable
- aliyun-oss-python-sdk Github地址:https://github.com/aliyun/aliyun-oss-python-sdk/tree/master/oss2