Linux环境Shell脚本上传下载阿里云OSS文件
背景
工作中由于我们项目生成的日志文件比较重要,而本地磁盘空间有限存储不了多久,因此考虑备份方案,我们原本打算保存在nas上,然而由于各种原因与运维沟通下来建议保存到oss上面。
由于linux原生支持shell,而网上大多数方案基于python-sdk,因此我们为了减少依赖,考虑直接使用shell脚本上传OSS,网上找了些资料,参见:
坑
然而脚本试用下来有坑,特地记录一下:
- 字符比较提示异常

上面截图字符比较会提示:
1./oss.sh: 13: ./oss.sh: [get: not found 2./oss.sh: 16: ./oss.sh: [put: not found 3./oss.sh: 32: ./oss.sh: [put: not found
应该改成上面的格式
2.拼接url的时候把bucket也带进去了。 3.拼接签名不对,研究了很久发现不应该用“#!/bin/sh”,而需要使用“#!/bin/bash”,这是个大坑。。。
修改版本
下面给出修改版本,需要自取:
1#!/bin/bash 2 3host="oss-cn-shanghai.aliyuncs.com" 4bucket="bucket名" 5Id="AccessKey ID" 6Key="Access Key Secret" 7# 参数1,PUT:上传,GET:下载 8method=$1 9# 参数2,上传时为本地源文件路径,下载时为oss源文件路径 10source=$2 11# 参数3,上传时为OSS目标文件路径,下载时为本地目标文件路径 12dest=$3 13 14osshost=$bucket.$host 15 16# 校验method 17if test -z "$method" 18then 19 method=GET 20fi 21 22if [ "${method}"x = "get"x ] || [ "${method}"x = "GET"x ] 23then 24 method=GET 25elif [ "${method}"x = "put"x ] || [ "${method}"x = "PUT"x ] 26then 27 method=PUT 28else 29 method=GET 30fi 31 32#校验上传目标路径 33if test -z "$dest" 34then 35 dest=$source 36fi 37 38echo "method:"$method 39echo "source:"$source 40echo "dest:"$dest 41 42#校验参数是否为空 43if test -z "$method" || test -z "$source" || test -z "$dest" 44then 45 echo $0 put localfile objectname 46 echo $0 get objectname localfile 47 exit -1 48fi 49 50if [ "${method}"x = "PUT"x ] 51then 52 resource="/${bucket}/${dest}" 53 contentType=`file -ib ${source} |awk -F ";" '{print $1}'` 54 dateValue="`TZ=GMT date +'%a, %d %b %Y %H:%M:%S GMT'`" 55 stringToSign="${method}\n\n${contentType}\n${dateValue}\n${resource}" 56 signature=`echo -en $stringToSign | openssl sha1 -hmac ${Key} -binary | base64` 57 echo $stringToSign 58 echo $signature 59 url=http://${osshost}/${dest} 60 echo "upload ${source} to ${url}" 61 curl -i -q -X PUT -T "${source}" \ 62 -H "Host: ${osshost}" \ 63 -H "Date: ${dateValue}" \ 64 -H "Content-Type: ${contentType}" \ 65 -H "Authorization: OSS ${Id}:${signature}" \ 66 ${url} 67else 68 resource="/${bucket}/${source}" 69 contentType="" 70 dateValue="`TZ=GMT date +'%a, %d %b %Y %H:%M:%S GMT'`" 71 stringToSign="${method}\n\n${contentType}\n${dateValue}\n${resource}" 72 signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${Key} -binary | base64` 73 url=http://${osshost}/${source} 74 echo "download ${url} to ${dest}" 75 curl --create-dirs \ 76 -H "Host: ${osshost}" \ 77 -H "Date: ${dateValue}" \ 78 -H "Content-Type: ${contentType}" \ 79 -H "Authorization: OSS ${Id}:${signature}" \ 80 ${url} -o ${dest} 81fi 82
执行命令:
1#上传 2$ ./oss.sh put a.gz c.gz 3 4#下载 5$ ./oss.sh get c.gz d.gz
2018-11-21更新:
今天看到阿里云提供ossutil64,详见:https://help.aliyun.com/document_detail/50452.html 有了这个方便很多。