Last active
August 29, 2018 21:20
-
-
Save dhaninugraha/0f4394cec1c5d90dbb9958f5d59a940a to your computer and use it in GitHub Desktop.
List blobs in an Azure blob storage container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bs4 import BeautifulSoup # optional; be sure to install this & lxml if you're following this example | |
import requests | |
import sys | |
def create_rfc_1123_datetime(): | |
from wsgiref.handlers import format_date_time | |
from datetime import datetime | |
from time import mktime | |
now = datetime.now() | |
stamp = mktime(now.timetuple()) | |
return format_date_time(stamp) | |
def create_sig(secret, to_sign): | |
import hmac | |
import hashlib | |
import base64 | |
# https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key#encoding-the-signature | |
dig = hmac.new(base64.b64decode(secret), msg=to_sign, digestmod=hashlib.sha256).digest() | |
return base64.b64encode(dig) | |
# let's assume we have an Azure storage account named "xxx" with a container named "foo" inside it | |
account = "xxx" # https://xxx.blob.core.windows.net/ | |
secret = "..." # Storage Accounts > xxx > Access Keys > value of 'Key' field from either key1 or key2 | |
now_rfc_1123 = create_rfc_1123_datetime() | |
x_ms_version = "2017-07-29" | |
params = ["comp:list", "restype:container"] | |
container = "foo" | |
to_sign = "GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:{}\nx-ms-version:{}\n/{}/{}\n{}".format( | |
now_rfc_1123, | |
x_ms_version, | |
account, | |
container, | |
"\n".join(params) | |
) | |
url = "https://{}.blob.core.windows.net/{}?{}".format( | |
account, | |
container, | |
"&".join([p.replace(":", "=") for p in params]) | |
) | |
try: | |
headers = { | |
"Authorization": "SharedKey {}:{}".format(account, create_sig(secret, to_sign)), | |
"x-ms-version": x_ms_version, | |
"x-ms-date": now_rfc_1123 | |
} | |
r = requests.get(url, headers=headers) | |
print r.status_code | |
if r.status_code is 200: | |
soup = BeautifulSoup(r.text, "xml") | |
print soup.prettify() | |
except Exception, e: | |
print "Line {}: {}".format(sys.exc_info()[-1].tb_lineno, e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment