Linux下无需任何SDK,一条shell命令搞定签名的上传和下载-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

Linux下无需任何SDK,一条shell命令搞定签名的上传和下载

wood23 2015-03-18 21:11:36 19355
感谢这位大侠
tmont.com/blargh/2014/1/uploading-to-s3-in-bash
实现了shell的签名上传
在这个基础上我做了一个OSS的上传和下载的shell命令,有兴趣的可以自己尝试下。

使用的前提条件:
就是必须安装了openssl和base64,curl这几个bianry,如果没有的,请自行搜索下安装
假如将以下代码保存为oss.sh
并将host,bucket,Id和Key替换成相应的OSS Host,Bucket,Id和Key

上传:
sh oss.sh put localfile objectname

成功的结果类似:

HTTP/1.1 200 OK
Date: Wed, 18 Mar 2015 12:55:23 GMT
Content-Length: 0
Connection: close
ETag: "A797938C31D59EDD08D86188F6D5B872"
Server: AliyunOSS
x-oss-request-id: 550975BB9215222B22015250

下载
sh oss.sh get objectname localfile


#!/bin/sh
host=需要修改
bucket=需要修改
Id=需要修改
Key=需要修改


method=$1
source=$2
dest=$3
if test -z "$method"
then
    method=GET
fi


if [ "get" = ${method} ] || [ "GET" = ${method} ]
then
    method=GET
elif [ "put" = ${method} ] || [ "PUT" = ${method} ]
then
    method=PUT
else
    method=GET
fi
if test -z "$dest"
then
    dest=$source
fi


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 [ "put" = ${method} ] || [ "PUT" = ${method} ]
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`
    url=http://${host}/${resource}
    echo "upload ${source} to ${url}"
    curl -i -q -X PUT -T "${source}" \
      -H "Host: ${host}" \
      -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://${host}/${resource}
    echo "download ${url} to ${dest}"
    curl --create-dirs \
      -H "Host: ${host}" \
      -H "Date: ${dateValue}" \
      -H "Content-Type: ${contentType}" \
      -H "Authorization: OSS ${Id}:${signature}" \
      ${url} -o ${dest}
fi

机器学习/深度学习 Shell Linux 开发工具 对象存储 Perl
分享到
取消 提交回答
全部回答(4)
  • boyang.liu
    2015-12-03 16:59:10
    ReLinux下无需任何SDK,一条shell命令搞定签名的上传和下载
    高手啊!必须学习一下
    0 0
  • rockuw
    2015-12-03 16:30:21
    ReLinux下无需任何SDK,一条shell命令搞定签名的上传和下载
    0 0
  • 中郁
    2015-12-03 16:24:40
    ReLinux下无需任何SDK,一条shell命令搞定签名的上传和下载
    神器啊
    0 0
  • ftp4oss
    2015-03-18 22:40:09
    高手!支持!
    0 0
添加回答

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题