linux本地遠程上傳&下載阿里雲oss的shell腳本實現方法


當項目早服務器中運行時會產生大量的日志,如果日志不處理全部放在本服務器中顯然沒有那么大的內存,除了要做必要的刪除也要做日志必要備份.

創建oss.sh腳本:

#!/bin/bash
host="oss-cn-beijing.aliyuncs.com"
bucket="****"
###bucket名字###
Id="****************"
###Access ID###
Key="******************"
###Access Key###
# 參數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

接下來執行shell腳本

上傳:sh /oss.sh put /要上傳文件/ /到oss指定地址

eg:sh oss.sh put /home/log.zip logs/log.zip
下載:sh /oss.sh get /要下載的文件/ /到linux本地地址
eg:sh oss.sh get /logs/log.zip /home/log.zip

當執行完以上命令出現如下圖就代表成功

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM