文档章节

【对象存储】【AWS2认证】

wzyuliyang
 wzyuliyang
发布于 2017/09/11 22:22
字数 825
阅读 28
收藏 0

ceph中的REST接口有S3 & Swift & Admin Rest Api,其中 S3和 Admin Rest Api都可以使用S3 的v2认证

curl版本

查询子账户的请求次数

#!/usr/bin/env bash
KEY_ACCESS="yly"
KEY_SECRET="yly"
relativePath="/admin/usage"
cmd="${relativePath}?format=json&uid=yly&subuser=swift"
current=`TZ=GMT LANG=en_US date "+%a, %d %b %Y %H:%M:%S GMT"`
stringToSign="GET\n\n\n${current}\n${relativePath}"
signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${KEY_SECRET} -binary | base64`
HOST="127.0.0.1"

curl -s -v -X GET "http://${HOST}${cmd}" \
-H "Authorization: AWS ${KEY_ACCESS}:${signature}" \
-H "Date: ${current}" \
-H "Host: ${HOST}"

创建桶

#!/usr/bin/env bash
KEY_ACCESS="admin"
KEY_SECRET="admin"
BUCKET="create-by-curl"
relativePath="/${BUCKET}"
current=`TZ=GMT LANG=en_US date "+%a, %d %b %Y %H:%M:%S GMT"`
stringToSign="PUT\n\n\n${current}\n${relativePath}"
signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${KEY_SECRET} -binary | base64`
HOST="yuliyangdebugwebjewel.tunnel.qydev.com"

curl -s -v -X PUT "http://${HOST}${relativePath}" \
-H "Authorization: AWS ${KEY_ACCESS}:${signature}" \
-H "Date: ${current}" \
-H "Host: ${HOST}"

上传对象

#!/usr/bin/env bash
KEY_ACCESS="admin"
KEY_SECRET="admin"
file="/root/admin2.py"
content_type=`file --mime-type $file | awk '{print $2}'`
BUCKET="create-by-curl"
OBJECT="OBJ3"
relativePath="/${BUCKET}/${OBJECT}"
current=`TZ=GMT LANG=en_US date "+%a, %d %b %Y %H:%M:%S GMT"`
stringToSign="PUT\n\n$content_type\n${current}\n${relativePath}"
signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${KEY_SECRET} -binary | base64`
HOST="yuliyangdebugwebjewel.tunnel.qydev.com"
#HOST="192.168.10.10:7480"
curl -v -X PUT -T "${file}" \
-H "Authorization: AWS ${KEY_ACCESS}:${signature}" \
-H "Date: ${current}" \
-H "Host: ${HOST}" \
-H "Expect:" \
-H "Content-Type: $content_type" \
"http://${HOST}${relativePath}"

删除对象

#!/usr/bin/env bash
KEY_ACCESS="admin"
KEY_SECRET="admin"
file="/root/10M"
content_type=`file --mime-type $file | awk '{print $2}'`
BUCKET="testusage"
OBJECT="10M"
relativePath="/${BUCKET}/${OBJECT}"
current=`TZ=GMT LANG=en_US date "+%a, %d %b %Y %H:%M:%S GMT"`
stringToSign="DELETE\n\n\n${current}\n${relativePath}"
signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${KEY_SECRET} -binary | base64`
#HOST="yuliyangdebugwebjewel.tunnel.qydev.com"
HOST="127.0.0.1:7480"
curl -s -v -X DELETE "http://${HOST}${relativePath}" \
-H "Authorization: AWS ${KEY_ACCESS}:${signature}" \
-H "Date: ${current}" \
-H "Host: ${HOST}"

python版本

# -*- coding: utf-8 -*-
import hmac

from hashlib import sha1 as sha

py3k = False
try:
    from urlparse import urlparse, unquote
    from base64 import encodestring
except:
    py3k = True
    from urllib.parse import urlparse, unquote
    from base64 import encodebytes as encodestring

from email.utils import formatdate

from requests.auth import AuthBase


class S3Auth(AuthBase):
    """Attaches AWS Authentication to the given Request object."""

    service_base_url = 's3.amazonaws.com'
    # List of Query String Arguments of Interest
    special_params = [
        'acl', 'location', 'logging', 'partNumber', 'policy', 'requestPayment',
        'torrent', 'versioning', 'versionId', 'versions', 'website', 'uploads',
        'uploadId', 'response-content-type', 'response-content-language',
        'response-expires', 'response-cache-control', 'delete', 'lifecycle',
        'response-content-disposition', 'response-content-encoding', 'tagging',
        'notification', 'cors', 'syncing'
    ]

    def __init__(self, access_key, secret_key, service_url=None):
        if service_url:
            self.service_base_url = service_url
        self.access_key = str(access_key)
        self.secret_key = str(secret_key)

    def __call__(self, r):
        # Create date header if it is not created yet.
        if 'date' not in r.headers and 'x-amz-date' not in r.headers:
            r.headers['date'] = formatdate(
                timeval=None,
                localtime=False,
                usegmt=True)
        signature = self.get_signature(r)
        if py3k:
            signature = signature.decode('utf-8')
        r.headers['Authorization'] = 'AWS %s:%s' % (self.access_key, signature)
        return r

    def get_signature(self, r):
        canonical_string = self.get_canonical_string(
            r.url, r.headers, r.method)
        if py3k:
            key = self.secret_key.encode('utf-8')
            msg = canonical_string.encode('utf-8')
        else:
            key = self.secret_key
            msg = canonical_string
        h = hmac.new(key, msg, digestmod=sha)
        return encodestring(h.digest()).strip()

    def get_canonical_string(self, url, headers, method):
        parsedurl = urlparse(url)
        objectkey = parsedurl.path[1:]
        query_args = sorted(parsedurl.query.split('&'))

        bucket = parsedurl.netloc[:-len(self.service_base_url)]
        if len(bucket) > 1:
            # remove last dot
            bucket = bucket[:-1]

        interesting_headers = {
            'content-md5': '',
            'content-type': '',
            'date': ''}
        for key in headers:
            lk = key.lower()
            try:
                lk = lk.decode('utf-8')
            except:
                pass
            if headers[key] and (lk in interesting_headers.keys()
                                 or lk.startswith('x-amz-')):
                interesting_headers[lk] = headers[key].strip()

        # If x-amz-date is used it supersedes the date header.
        if not py3k:
            if 'x-amz-date' in interesting_headers:
                interesting_headers['date'] = ''
        else:
            if 'x-amz-date' in interesting_headers:
                interesting_headers['date'] = ''

        buf = '%s\n' % method
        for key in sorted(interesting_headers.keys()):
            val = interesting_headers[key]
            if key.startswith('x-amz-'):
                buf += '%s:%s\n' % (key, val)
            else:
                buf += '%s\n' % val

        # append the bucket if it exists
        if bucket != '':
            buf += '/%s' % bucket

        # add the objectkey. even if it doesn't exist, add the slash
        buf += '/%s' % objectkey

        params_found = False

        # handle special query string arguments
        for q in query_args:
            k = q.split('=')[0]
            if k in self.special_params:
                buf += '&' if params_found else '?'
                params_found = True

                try:
                    k, v = q.split('=', 1)

                except ValueError:
                    buf += q
                else:
                    buf += '{key}={value}'.format(key=k, value=unquote(v))

        return buf


import requests
import logging
from requests_toolbelt.utils import dump
logging.basicConfig(level=logging.DEBUG)
access_key = 'yly'
secret_key = 'yly'
url = 'http://bucket1.s3.amazonaws.com/?website'
response = requests.get(url, auth=S3Auth(access_key, secret_key,service_url='s3.amazonaws.com'))
#response = requests.put(url, auth=S3Auth(access_key, secret_key,service_url='s3.amazonaws.com'),data='''<?xml version="1.0" encoding="UTF-8"?><WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><IndexDocument><Suffix>index.html</Suffix></IndexDocument><ErrorDocument><Key>error.html</Key></ErrorDocument></WebsiteConfiguration>''')
data = dump.dump_all(response)
print(data.decode('utf-8'))

© 著作权归作者所有

共有 人打赏支持
wzyuliyang
粉丝 3
博文 20
码字总数 16746
作品 1
苏州
程序员
块存储、文件存储、对象存储这三者和分布式文件存储系统的本质区别

块存储和文件存储是我们比较熟悉的两种主流的存储类型,而对象存储(Object-based Storage)是一种新的网络存储架构,基于对象存储技术的设备就是对象存储设备(Object-based Storage Device...

English0523
2016/05/18
0
0
对象存储为什么能吸引很多对象 五大技术优势彰显存储魅力

大家众说纷“云”,其中,云存储已经成为业界最为火热的概念之一。大数据时代,没有存储或存储技术,一切都将成为“浮云”! 对象存储本身是一种与传统完全不同的解决方案,类似于当前正在兴起...

玄学酱
05/09
0
0

没有更多内容

加载失败,请刷新页面

加载更多
零拷贝I:用户模式视角

英文原文地址:http://www.linuxjournal.com/article/6345。内容是关于 Zero Copy(零拷贝) 的详细介绍。在RocketMQ的Consumer 消费消息过程,使用了零拷贝技术。作用是即使被频繁调用,文件传...

Jacktanger
19分钟前
9
0
记在k8s的pod上使用apache的commons-net:ftp功能时,ftp一直上传文件失败

在k8s的pod上使用apache的commons-net:ftp功能时,一直显示: 即上传文件失败,但是在本地环境进行上传时却又显示上传成功,让人十分不解。在网上搜索了一下ftp的一些资料发现ftp共有两种模式...

helplove
19分钟前
1
0
Go map实现原理

map数据结构 Golang的map使用哈希表作为底层实现,一个哈希表里可以有多个哈希表节点,也即bucket,而每个bucket就保存了map中的一个或一组键值对。 map数据结构由runtime/map.go/hmap定义:...

恋恋美食
26分钟前
1
0
debian python library re-install

apt-get install python-aptsudo apt-get install python-pkg-resources python-setuptools --reinstall...

关上越
31分钟前
1
0
Elasticsearch地理位置总结

更多内容请参考 : https://www.felayman.com 翻译版本:https://es.xiaoleilu.com/310_Geopoints/00_Intro.html 官方原文:https://www.elastic.co/guide/en/elasticsearch/guide/current/g......

xiaomin0322
31分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部