我有一个现有的存储帐户/容器,我可以在其中使用 AZ CLI 列出所有 blob:
[ ~ ]$ az storage blob list --account-name storageaccount20122022 --container-name test
There are no credentials provided in your command and environment, we will query for account key for your storage account.
It is recommended to provide --connection-string, --account-key or --sas-token in your command as credentials.
You also can add `--auth-mode login` in your command to use Azure Active Directory (Azure AD) for authorization if your login account is assigned required RBAC roles.
For more information about RBAC roles in storage, visit https://docs.microsoft.com/azure/storage/common/storage-auth-aad-rbac-cli.
In addition, setting the corresponding environment variables can avoid inputting credentials in your command. Please use --help to get more information about environment variable usage.
[
{
"container": "test",
"content": "",
...
}
]
我想用 Python 做同样的事情,这是我的脚本:
import sys
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
def list_blobs_using_cli_credential(account_name, container_name):
credential = DefaultAzureCredential() # Also tried AzureCliCredential()
blob_service_client = BlobServiceClient(
account_url=f"https://{account_name}.blob.core.windows.net",
credential=credential
)
container_client = blob_service_client.get_container_client(container_name)
print(f"Listing blobs in {account_name}/{container_name} ...")
try:
blobs = container_client.list_blobs()
for blob in blobs:
print(blob.name)
except Exception as e:
print(f"Error listing blobs: {e}")
if __name__ == "__main__":
account_name = sys.argv[1]
container_name = sys.argv[2]
list_blobs_using_cli_credential(account_name, container_name)
但是,当我在同一个 shell 中运行它时,我收到错误:
[ ~ ]$ python list-blobs.py storageaccount20122022 test
Listing blobs in storageaccount20122022/test ...
Error listing blobs: This request is not authorized to perform this operation using this permission.
RequestId:466b2647-201e-0022-13fd-918e18000000
Time:2024-04-19T01:59:22.6413231Z
ErrorCode:AuthorizationPermissionMismatch
Content: <?xml version="1.0" encoding="utf-8"?><Error><Code>AuthorizationPermissionMismatch</Code><Message>This request is not authorized to perform this operation using this permission.
RequestId:466b2647-201e-0022-13fd-918e18000000
Time:2024-04-19T01:59:22.6413231Z</Message></Error>
我可以通过 Python 列出存储帐户和每个帐户中的容器,但是当涉及到处理 Blob(列表、删除、上传)时,我无法通过 Python 执行任何操作,而相同的操作可以通过 AZ CLI 进行。
我尝试了两个不同的Azure帐户,完全不相关,其中一个帐户我是所有者,但它仍然是相同的。
AZ CLI 正在做什么,它会自动获取哪些其他权限或角色来执行 Blob 操作?我怎样才能在我的 Python 代码中做同样的事情?
当 AZ CLI 使用相同的凭据时,从 Python 列出 blob 时获取错误代码:AuthorizationPermissionMismatch。
Azure CLI
命令将与 Owner 访问权限一起使用,以列出存储帐户中的 Blob,但使用 Python 时,可能需要特定角色,例如Storage Blob Data Contributor,才能成功操作.
我在订阅级别具有 Owner 角色。我可以使用
Azure CLI
列出斑点,但不能使用 Python
。
Azure CLI 命令结果
Python代码结果
分配 Storage Blob Data Contributor 角色后,我可以在
blobs
中列出所有 container
。
分配角色后的Python代码结果。