我使用 Azure CLI 将资源组中的数据库备份导出到 blobstorage ,因此我想在 python脚本上使用相同的命令 >。
例如,我在Azure CLI中使用以下命令导出资源组中的数据库:
az sql db export -s (sql server) -n (database) -g (group) -p (password)
-u login --storage-key " key "
--storage-key-type
--storage-uri (url blob)
我该如何使用Python脚本来实现这一目标?
答案 0 :(得分:0)
您可以使用Python中的REST API将Azure SQL数据库导出为bacpac。
这是一个示例请求。
POST https://management.azure.com/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/sqlcrudtest-4799/providers/Microsoft.Sql/servers/sqlcrudtest-5961/databases/testdb/export?api-version=2014-04-01
请求正文。
{
"storageKeyType": "SharedAccessKey",
"storageKey": "?sr=b&sp=rw&se=2018-01-01T00%3A00%3A00Z&sig=sdfsdfklsdjflSLIFJLSIEJFLKSDJFDd/%2wdfskdjf3%3D&sv=2015-07-08",
"storageUri": "https://test.blob.core.windows.net/bacpacs/testbacpac.bacpac",
"administratorLogin": "dummyLogin",
"administratorLoginPassword": "Un53cuRE!",
"authenticationType": "SQL"
}
样本响应。
{
"id": "/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/sqlcrudtest-4799/providers/Microsoft.Sql/servers/sqlcrudtest-5961/importExportOperationResult/f01d7bfe-7162-44e7-9350-f1c85ce83e4c",
"name": "f01d7bfe-7162-44e7-9350-f1c85ce83e4c",
"type": "Microsoft.Sql/servers/importExportOperationResults",
"properties": {
"requestId": "f01d7bfe-7162-44e7-9350-f1c85ce83e4c",
"requestType": "Export",
"queuedTime": "3/1/2017 12:14:25 AM",
"lastModifiedTime": "3/1/2017 12:16:33 AM",
"blobUri": "https://test.blob.core.windows.net/bacpacs/test.bacpac",
"serverName": "test",
"databaseName": "testdb",
"status": "Completed",
"errorMessage": null
}
}
答案 1 :(得分:0)
请确保使用pip安装 azure-mgmt-sql == 0.16.0 软件包。
在以下代码段中调整参数,您应该会很好。
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.sql import SqlManagementClient
from azure.mgmt.sql.models import StorageKeyType, AuthenticationType
from msrestazure.azure_exceptions import CloudError
TENANT_ID = '<your_tennant_id>'
CLIENT = '<your_client_id>'
KEY = '<your_client_key>'
SUBSCRIPTION_ID = '<your_subscription_id>'
credentials = ServicePrincipalCredentials(
client_id=CLIENT,
secret=KEY,
tenant=TENANT_ID
)
sql_client = SqlManagementClient(credentials, SUBSCRIPTION_ID)
kwargs = dict()
kwargs['storage_key_type'] = 'StorageAccessKey'
kwargs['storage_key'] = '<your_storage_account_key'
kwargs['storage_uri'] = 'https://<name>.blob.core.windows.net/<container>/<name>.bacpac'
kwargs['administrator_login'] = '<admin_name>'
kwargs['administrator_login_password'] = '<admin_password>'
kwargs['authentication_type'] = 'SQL'
try:
poller = sql_client.databases.export(
database_name='<your_db_name>',
server_name='<your_server_name>',
resource_group_name='<your_rg_name>',
storage_key_type='StorageAccessKey',
storage_key='<your_storage_account_key',
parameters=kwargs)
print(poller.result())
except CloudError as err:
print(err.error)
print(err.message)