使用说明及注意:
- 脚本里面的accessKeyId和AccessSecret别泄露
- 运行命令格式:sh aliyunOss.sh 本机源文件夹 oss目的文件夹
- 两个参数【本机源文件夹】【oss目的文件夹】的前后不要有斜杠
- 此脚本运行后直接上传在脚本里面topDirName配置的目录下的
- 示例:如【本机源文件夹】的是:dist/static,【oss目的文件夹】:dir1/dir2,则会在oss下创建dir1/dir2目录,并且源文件夹dist/static在dir2文件夹。运行命令如:sh aliyunOss.sh dist/static dir1/dir2
#!/bin/bash
#oos全局参数配置 !!!!!!!!!!勿泄漏!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
host="oss-cn-shenzhen.aliyuncs.com"
bucket="xxxxxxxxx" # BucketName
accessKeyId="xxxxxxxxx" # AccessKeyId
AccessKeySecret="xxxxxxxxx" # AccessKeySecret
osshost=$bucket.$host
topDirName=xxxx #桶的顶级目录名,不写的话直接上传到桶的根目录
#第一个参数是文件或文件夹
sourceFileOrDir=$1
#第二个参数是需要传到oss的目录,相对于上面topDirName的目录下的,不传这个参数则直接传到topDirName设置的目录下
destDir=$2
#上传到oss文件对象个数计数,文件夹也算一个对象
uploadOssObjectCount=0
#需要两个参数
#第一个入参:源文件,如a.txt
#第二个入参:上传oss的指定的目录下面
function uploadFileToOss(){
cur_source=$1
cur_dest=$2
echo "正在上传【${cur_source}】到oss【${cur_dest}】......."
resource="/${bucket}/${topDirName}/${cur_dest}"
contentType=`file -ib $cur_source |awk -F ";" '{print $1}'`
dateValue="`TZ=GMT env LANG=en_US.UTF-8 date +'%a, %d %b %Y %H:%M:%S GMT'`"
stringToSign="PUT\n\n${contentType}\n${dateValue}\n${resource}"
signature=`echo -en $stringToSign | openssl sha1 -hmac ${AccessKeySecret} -binary | base64`
url=http://${osshost}/${topDirName}/${cur_dest}
echo "upload ${cur_source} to ${url}"
responseContent=`curl -i -q -X PUT -T "${cur_source}" \
-H "Host: ${osshost}" \
-H "Date: ${dateValue}" \
-H "Content-Type: ${contentType}" \
-H "Authorization: OSS ${accessKeyId}:${signature}" \
${url}`;
uploadOssObjectCount=`expr $uploadOssObjectCount + 1`;
}
#检索参数指定的待上传的目录,上传到指定的oss目录下
function recursion_dir(){
curPath=$1
for pathname in "$curPath"/*
do
if [ -d "$pathname" ]
then
recursion_dir "$pathname"
else
#echo "pathname:${pathname}"
uploadFileToOss "${pathname}" "${destDir}/${pathname}"
fi
done
}
#判断上传的是目录还是文件
if [ -d $sourceFileOrDir ]
then
#调用文件夹上传
recursion_dir $sourceFileOrDir
else
#直接调用oss上传
uploadFileToOss $sourceFileOrDir "$destDir/$sourceFileOrDir"
fi
echo "上传完成:总共上传${uploadOssObjectCount}个对象到OSS"