文档章节

【对象存储】【AWS2认证】

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

wzyuliyang

粉丝 4
博文 20
码字总数 16746
作品 1
苏州
程序员
私信 提问
加载中
请先登录后再评论。
对象存储的发展历程(下)——从软件到服务的“升级”

导语 在《从“软件”到“服务”——【对象存储】的发展历程(上)》中,我们和大家在对象存储大规模普及之前,大量的数据存储和处理是怎么实现的。但这些方案大都专注于解决其中一类问题,缺...

京东云技术新知
2019/05/08
113
0
一点小感悟关于df lsblk fdisk命令关于三种存储

物理块与文件系统之间的关系图: 映射关系:扇区→物理块→逻辑块→文件系统 dfisk:物理块 lsblk:逻辑块 df:文件系统 分布式存储的应用场景根据其存储接口,即提供的访问接口,现在流行分为...

osc_8iux0cyz
2019/09/27
3
0
从“软件”到“服务“——【对象存储】的发展历程(上)

导语 据IDC的分析师预测,2025年,全球范围内的数据量将增长到163 ZB,相较于2016年的16.1 ZB,十年间将增长1000%。面对飞速增长的数据量,企业和机构在未来又将如何存储这些数据呢? 本文将...

京东云技术新知
2019/03/06
9
0
京东智联云在 Serverless 的探索

本文整理自 ServerlessDay · China 大会 - 《京东智联云在 Serverless 的探索》的分享,讲师为京东智联云的 PaaS 产品负责⼈朱琅。 本文主要分为三部分: ⾸先会介绍下 Serverless 的概念和...

osc_2frf70qv
07/29
3
0
京东智联云在 Serverless 的探索

本文整理自 ServerlessDay · China 大会 - 《京东智联云在 Serverless 的探索》的分享,讲师为京东智联云的 PaaS 产品负责⼈朱琅。 本文主要分为三部分: ⾸先会介绍下 Serverless 的概念和...

腾讯云Serverless
07/28
10
0

没有更多内容

加载失败,请刷新页面

加载更多

android 获取mac地址

android获取Mac地址的两种方式,适用于6.0版本以下 public static String tryGetWifiMac(Context context) { WifiManager wm = (WifiManager) context.getApplicationContext().getSyst......

osc_8cqhsn24
28分钟前
0
0
阿里HR: 你会 Android 实现侧滑菜单-design吗? CN看了,原来这么简单呀!

google提供的Design开发包里,有很多实用好看的新控件,这里介绍下使用DrawerLayout+NavigationView实现侧滑菜单效果 要使用Design包,只要在项目的build.gradle中添加下依赖就好(记得更新S...

osc_evac23lh
30分钟前
0
0
IOS开发控件视图day15:UIPageControl设置定时器自动翻页,以及更改小圆点背景图片

.h文件 @property(nonatomic,strong)UIScrollView *scrollView0;@property (strong, nonatomic) UIPageControl *pageControl0;@property (nonatomic,strong) NSTimer *nstime; .m文件(具......

osc_494omtst
30分钟前
0
0
Codeforces Round #663 (Div. 2) (CD)

C. Cyclic Permutations 思路:全排列减去单峰排列即为答案。 单峰排列即:峰左边下标的左边没有比它大的,峰右边的下标的右边没有比它大的。 单峰排列个数: 2 n − 1 2^{n-1} 2n−1,除 n ...

osc_gh0ost1g
32分钟前
0
0
Python Pandas面试题及答案

Pandas是一个开源库,可在Python中提供高性能的数据处理。 Pandas这个名称源自“面板数据”一词,这表示来自多维数据的计量经济学。 它可用于Python中的数据分析,并由Wes McKinney在2008年开...

程序员面试吧
32分钟前
10
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部