开发者社区> 问答> 正文

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

感谢这位大侠
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

展开
收起
wood23 2015-03-18 21:11:36 27622 0
6 条回答
写回答
取消 提交回答
  • 报错OSS authentication requires a valid Date.

    2020-04-17 15:29:05
    赞同 展开评论 打赏
  • 大神你好,通过shell写了一个更新dns @主机记录的脚本,提示签名失败,有时间帮忙看下吗

    2020-02-25 14:51:17
    赞同 展开评论 打赏
  • ReLinux下无需任何SDK,一条shell命令搞定签名的上传和下载
    高手啊!必须学习一下
    2015-12-03 16:59:10
    赞同 展开评论 打赏
  • Serverless | Function Compute
    ReLinux下无需任何SDK,一条shell命令搞定签名的上传和下载
    2015-12-03 16:30:21
    赞同 展开评论 打赏
  • ReLinux下无需任何SDK,一条shell命令搞定签名的上传和下载
    神器啊
    2015-12-03 16:24:40
    赞同 展开评论 打赏
  • 高手!支持!
    2015-03-18 22:40:09
    赞同 展开评论 打赏
滑动查看更多
问答排行榜
最热
最新

相关电子书

更多
Alibaba Cloud Linux 3 发布 立即下载
ECS系统指南之Linux系统诊断 立即下载
ECS运维指南 之 Linux系统诊断 立即下载