Linux環境Shell腳本上傳下載阿里雲OSS文件

Linux環境Shell腳本上傳下載阿里雲OSS文件

背景

工做中因爲咱們項目生成的日誌文件比較重要,而本地磁盤空間有限存儲不了多久,所以考慮備份方案,咱們本來打算保存在nas上,然而因爲各類緣由與運維溝通下來建議保存到oss上面。html

因爲linux原生支持shell,而網上大多數方案基於python-sdk,所以咱們爲了減小依賴,考慮直接使用shell腳本上傳OSS,網上找了些資料,參見:python

然而腳本試用下來有坑,特意記錄一下:linux

  1. 字符比較提示異常

字符比較

上面截圖字符比較會提示:shell

./oss.sh: 13: ./oss.sh: [get: not found
./oss.sh: 16: ./oss.sh: [put: not found
./oss.sh: 32: ./oss.sh: [put: not found

應該改爲上面的格式bash

2.拼接url的時候把bucket也帶進去了。 3.拼接簽名不對,研究了好久發現不該該用「#!/bin/sh」,而須要使用「#!/bin/bash」,這是個大坑。。。運維

修改版本

下面給出修改版本,須要自取:ssh

#!/bin/bash

host="oss-cn-shanghai.aliyuncs.com"
bucket="bucket名"
Id="AccessKey ID"
Key="Access Key Secret"
# 參數1,PUT:上傳,GET:下載
method=$1
# 參數2,上傳時爲本地源文件路徑,下載時爲oss源文件路徑
source=$2
# 參數3,上傳時爲OSS目標文件路徑,下載時爲本地目標文件路徑
dest=$3

osshost=$bucket.$host

# 校驗method
if test -z "$method"
then
    method=GET
fi

if [ "${method}"x = "get"x ] || [ "${method}"x = "GET"x ]
then
    method=GET
elif [ "${method}"x = "put"x ] || [ "${method}"x = "PUT"x ]
then
    method=PUT
else
    method=GET
fi

#校驗上傳目標路徑
if test -z "$dest"
then
    dest=$source
fi

echo "method:"$method
echo "source:"$source
echo "dest:"$dest

#校驗參數是否爲空
if test -z "$method" || test -z "$source" || test -z "$dest"
then
    echo $0 put localfile objectname
    echo $0 get objectname localfile
    exit -1
fi

if [ "${method}"x = "PUT"x ]
then
    resource="/${bucket}/${dest}"
    contentType=`file -ib ${source} |awk -F ";" '{print $1}'`
    dateValue="`TZ=GMT date +'%a, %d %b %Y %H:%M:%S GMT'`"
    stringToSign="${method}\n\n${contentType}\n${dateValue}\n${resource}"
    signature=`echo -en $stringToSign | openssl sha1 -hmac ${Key} -binary | base64`
    echo $stringToSign
    echo $signature
    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}
else
    resource="/${bucket}/${source}"
    contentType=""
    dateValue="`TZ=GMT date +'%a, %d %b %Y %H:%M:%S GMT'`"
    stringToSign="${method}\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}
fi

執行命令:curl

#上傳
$ ./oss.sh put a.gz c.gz

#下載
$ ./oss.sh get c.gz d.gz

2018-11-21更新:阿里雲

今天看到阿里雲提供ossutil64,詳見:https://help.aliyun.com/document_detail/50452.html 有了這個方便不少。url

相關文章
相關標籤/搜索