You need to enable JavaScript to run this app. 如何在Azure Python 3 Runbook中配置SQL Token认证连接Azure SQL数据库?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Python 3 Runbook中配置SQL Token认证连接Azure SQL数据库?

Azure Runbook连接Azure SQL缺ODBC Driver的解决方案

提问原文:
我在Azure Runbook中部署了一段Python 3脚本,需通过Token认证连接Azure SQL Server数据库。当前遇到的问题是:Azure运行环境未预装ODBC Driver 17 for SQL Server,且我们无权对该运行环境进行管控。我曾尝试通过os.system('msiexec')命令强制在该环境安装对应驱动,但由于Windows Installer服务无法访问,该方案未生效。经测试我的代码在本地笔记本上可正常运行,因此排除代码本身故障,问题完全源于Azure运行环境缺少所需驱动。请问是否有可行的变通方案?
原有代码:

#!/usr/bin/env python3
    
import adal
from msrestazure.azure_active_directory import AADTokenCredentials
import pyodbc
import struct
    
resource = "x"
tenant = "x"
authorityHostUrl = "https://login.microsoftonline.com"
clientId = "x"
clientSecret = "x"
authority_uri = authorityHostUrl + '/' + tenant
resource_uri = 'https://database.windows.net/'
    
context = adal.AuthenticationContext(authority_uri, api_version=None)
mgmt_token = context.acquire_token_with_client_credentials(resource_uri, clientId, clientSecret)
token = mgmt_token["accessToken"]
    
SQL_COPT_SS_ACCESS_TOKEN = 1256 
driver = "{ODBC Driver 17 for SQL Server}"
server = "x.database.windows.net"
database = "x"
connString = "DRIVER=" + driver + ";SERVER=" + server + ";DATABASE=" + database +";Trusted_Connection=False;Encrypt=True;Integrated Security=False;"
    
tokenb = bytes(token, "UTF-8")
exptoken = b''
for i in tokenb:
    exptoken += bytes({i})
    exptoken += bytes(1)
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
    
conn = pyodbc.connect(connString, attrs_before = {SQL_COPT_SS_ACCESS_TOKEN:tokenstruct})
    
cursor = conn.cursor()
cursor.execute("SELECT TOP (5) * FROM Reference")
row = cursor.fetchone()
    
for i in row:
    print(i)
可行变通方案
  • 方案1:切换Azure Runbook运行环境为Linux沙盒
    • Azure自动化账户的Linux沙盒默认预装ODBC Driver 17 for SQL Server,不需要手动安装驱动
    • 切换后原有Python3代码基本无需调整,仅需确认驱动配置字符串与Linux环境下的注册名称匹配即可
  • 方案2:解压ODBC Driver17安装包到用户目录,跳过系统安装步骤
    • 无需调用Windows Installer服务,直接提取MSI安装包内的核心驱动DLL(msodbcsql17.dll及关联依赖)到Runbook可写入的用户目录
    • 原代码中driver配置不再使用系统注册的驱动名称,直接替换为解压后DLL的完整绝对路径,其余逻辑无需调整
  • 方案3:换用纯Python驱动pymssql,完全绕开ODBC依赖
    • pymssql自带静态编译的FreeTDS组件,不需要系统预装任何ODBC驱动,不需要管理员权限即可通过pip部署到Runbook环境
    • 无需手动构造Token结构体,直接将获取到的AAD访问令牌传入连接参数即可完成认证,适配后的核心代码示例:
import pymssql
# 沿用原有获取AAD Token的逻辑
conn = pymssql.connect(
    server="x.database.windows.net",
    database="x",
    token=token,
    encrypt=True
)
cursor = conn.cursor()
cursor.execute("SELECT TOP (5) * FROM Reference")
row = cursor.fetchone()
for i in row:
    print(i)

内容的提问来源于stack exchange,提问作者BrokenBad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 12:24:04