文档章节

【对象存储】【AWS2认证】

wzyuliyang
 wzyuliyang
发布于 2017/09/11 22:22
字数 825
阅读 32
收藏 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'))

© 著作权归作者所有

共有 人打赏支持
下一篇: 上传包到pypi
wzyuliyang
粉丝 3
博文 20
码字总数 16746
作品 1
苏州
程序员
私信 提问
块存储、文件存储、对象存储这三者和分布式文件存储系统的本质区别

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

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

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

玄学酱
05/09
0
0
[译]变量在 PHP7 内部的实现(二)

→ About → Links → Github → 公众号 Scholer's Blog [译]变量在 PHP7 内部的实现二 Dec 21, 2015 本文第一部分和第二均翻译自Nikita Popov(nikicPHP 官方开发组成员柏林科技大学的学生)...

污湖洞主
2017/06/11
0
0

没有更多内容

加载失败,请刷新页面

加载更多
设计模式之单例模式

单例模式核心:保证一个类只有一个对象 单例模式分为五种:懒汉式、饿汉式、双重检测锁式、静态内部类式、枚举式 五种模式的特点:懒汉式---线程安全,调用效率高,不能延时加载 饿汉式---线...

森林之下
17分钟前
0
0
markdown语法

这篇博客是本人在使用markdown语法过程中,用于记录一些自己总是会忘记的语法,并且会持续更新; 如何增加批注/备注:>; 这是一条备注/引言 如何手动换行,行末两次空格;

BlackCanary
18分钟前
1
0
redis 设置外网可访问

前提是你已经把redis的端口放到了防火墙计划中,  /sbin/iptables -I INPUT -p tcp --dport 6379 -j ACCEPT /etc/rc.d/init.d/iptables save 更改redis.conf 文件 bind 127.0.0.1prot...

时刻在奔跑
20分钟前
0
0
css3隐藏滚动条

chrome 和Safari .element::-webkit-scrollbar { width: 0 } IE 10+ .element { -ms-overflow-style: none; } Firefox .element { overflow: -moz-scrollbars-none; } firefox这个没试过~啦啦......

呵呵闯
36分钟前
0
0
Poco官方PPT_020-ErrorHandlingAndDebugging双语对照翻译

因工作需要用到这一块的功能,所以直接翻译了一下 此PPT来源于官方文件,地址https://pocoproject.org/documentation.html

CHONGCHEN
40分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部