且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法通过 python 连接到 azure 文件服务 REST api

更新时间:2022-06-22 22:02:10

我也推荐使用 Python SDK 但出于教育目的:

I also recommend to use Python SDK but for educational purposes:

import requests
import datetime
import hmac
import hashlib
import base64

storage_account_name = 'teststorageaccount'
storage_account_key = 'D4x6YChpyfqWk9a.......'
api_version = '2016-05-31'
request_time = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

string_params = {
    'verb': 'GET',
    'Content-Encoding': '',
    'Content-Language': '',
    'Content-Length': '',
    'Content-MD5': '',
    'Content-Type': '',
    'Date': '',
    'If-Modified-Since': '',
    'If-Match': '',
    'If-None-Match': '',
    'If-Unmodified-Since': '',
    'Range': '',
    'CanonicalizedHeaders': 'x-ms-date:' + request_time + '
x-ms-version:' + api_version + '
',
    'CanonicalizedResource': '/' + storage_account_name + '/
comp:list'
}

string_to_sign = (string_params['verb'] + '
' 
                  + string_params['Content-Encoding'] + '
'
                  + string_params['Content-Language'] + '
'
                  + string_params['Content-Length'] + '
'
                  + string_params['Content-MD5'] + '
' 
                  + string_params['Content-Type'] + '
' 
                  + string_params['Date'] + '
' 
                  + string_params['If-Modified-Since'] + '
'
                  + string_params['If-Match'] + '
'
                  + string_params['If-None-Match'] + '
'
                  + string_params['If-Unmodified-Since'] + '
'
                  + string_params['Range'] + '
'
                  + string_params['CanonicalizedHeaders']
                  + string_params['CanonicalizedResource'])

signed_string = base64.b64encode(hmac.new(base64.b64decode(storage_account_key), msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()).decode()

headers = {
    'x-ms-date' : request_time,
    'x-ms-version' : api_version,
    'Authorization' : ('SharedKey ' + storage_account_name + ':' + signed_string)
}

url = ('https://' + storage_account_name + '.file.core.windows.net/?comp=list')

r = requests.get(url, headers = headers)

print(r.content)

输出:

<?xml version="1.0" encoding="utf-8"?><EnumerationResults ServiceEndpoint="https://teststorageaccount.file.core.windows.net/"><Shares><Share><Name>myfileshare</Name><Properties><Last-Modified>Tue, 17 Apr 2018 13:43:00 GMT</Last-Modified><Etag>"0x8D5A46922CA8BDA"</Etag><Quota>10</Quota></Properties></Share></Shares><NextMarker /></EnumerationResults>