前提:
一般情况下对OSS操作都会通过SDK,但是很多情况下对OSS进行简单的上传下载的操作,那么SDK就显得有些臃肿,先要下载sdk包,然后再写些简单的操作脚本,而通过shell脚本就会简单很多。
而且很多场景:线上网站、数据库等,生产出来的网站数据、数据库数据、日志数据都需要来备份,如果备份再本地磁盘,那么没过多久磁盘空间就占用光了,如果是NAS来备份数据,价格又比较贵,如果把数据备份到OSS 低频存储就比较实惠一些。
使用方法:
上传文件到OSS:PUT
#!/bin/bash
host="oss-cn-shanghai.aliyuncs.com"
bucket="bucket名"
Id="AccessKey ID"
Key="Access Key Secret"
osshost=$bucket.$host
source="localfilename"
dest="objecetename"
resource="/${Bucket}/${dest}"
contentType=`file -ib ${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 ${Key} -binary | base64`
url=http://${OssHost}/${dest}
echo "upload ${source} to ${url}"
curl -i -q -X PUT -T "${source}" \
-H "Host: ${OssHost}" \
-H "Date: ${dateValue}" \
-H "Content-Type: ${contentType}" \
-H "Authorization: OSS ${Id}:${signature}" \
${url}
下载OSS的文件:GET
#!/bin/bash
host="oss-cn-shanghai.aliyuncs.com"
bucket="bucket名"
Id="AccessKey ID"
Key="Access Key Secret"
osshost=$bucket.$host
source="objecetename"
dest="localfilename"
resource="/${bucket}/${source}"
contentType=""
dateValue="`TZ=GMT env LANG=en_US.UTF-8 date +'%a, %d %b %Y %H:%M:%S GMT'`"
stringToSign="GET\n\n${contentType}\n${dateValue}\n${resource}"
signature=`echo -en $stringToSign | openssl sha1 -hmac ${Key} -binary | base64`
url=http://${osshost}/${source}
echo "download ${url} to ${dest}"
curl --create-dirs \
-H "Host: ${osshost}" \
-H "Date: ${dateValue}" \
-H "Content-Type: ${contentType}" \
-H "Authorization: OSS ${Id}:${signature}" \
${url} -o ${dest}