要在 Azure Ubuntu VM 上為 Python 安裝 Microsoft ODBC Driver 18,你需要完成兩個主要部分:安裝系統層級的驅動程式,以及安裝 Python 介面庫(通常是 pyodbc)。
請注意,ODBC Driver 18 預設啟用了加密連線(Encrypt=yes),這與舊版本(v17)不同,連線時可能需要調整連線字串。
第一步:安裝 Microsoft ODBC Driver 18
請根據你的 Ubuntu 版本執行以下指令(適用於 20.04, 22.04, 24.04):
導入 Microsoft 公鑰與來源清單
# 取得 Ubuntu 版本號 (如 22.04)
UBUNTU_VERSION=$(lsb_release -rs)
# 下載 Microsoft GPG 金鑰
curl https://packages.microsoft.com/keys/microsoft.asc | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc
# 加入 Microsoft Ubuntu 套件庫
curl https://packages.microsoft.com/config/ubuntu/$UBUNTU_VERSION/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list
安裝驅動程式與開發標頭檔
sudo apt-get update
ACCEPT_EULA=Y 會自動同意授權合約
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18 unixodbc-dev
上面這行在 Ubuntu 26.04 會出錯, 錯誤訊息:
E: The repository 'https://packages.microsoft.com/ubuntu/24.04/prod noble InRelease' is not signed.
This is a classic “security handshake” failure. Even though you added the repository link, apt is refusing to trust it because it can’t verify the digital signature. This usually happens if the GPG key wasn’t imported correctly or if there’s a conflict with how the key is stored in newer versions of Ubuntu (like 24.04 “Noble”).
To fix this, we need to manually fetch the key and ensure it’s placed where apt expects it for that specific repository.
1. Clear the “Bad” List
First, let’s remove the entry that is causing the error so we can start fresh:
Bash
sudo rm /etc/apt/sources.list.d/mssql-release.list
2. Properly Import the GPG Key
Ubuntu 24.04 is stricter about GPG keys. Instead of using apt-key (which is deprecated), use this method to download and de-armor the key:
Bash
curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --dearmor -o /usr/share/keyrings/microsoft-prod.gpg
3. Add the Repository with the Key Reference
Now, re-add the repository, but this time we will explicitly tell apt to use the keyring we just created to verify this specific URL:
Bash
echo "deb [arch=amd64,arm64,armhf signed-by=/usr/share/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/ubuntu/24.04/prod noble main" | sudo tee /etc/apt/sources.list.d/mssql-release.list
4. Update and Install
Now the signature check should pass:
Bash
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18 unixodbc-dev
What went wrong?
In modern Linux distributions, “un-signed” repositories are blocked by default to prevent “man-in-the-middle” attacks where someone could inject malicious software into your update stream. By using the signed-by flag in the .list file, you are creating a direct trust link between the Microsoft URL and the Microsoft GPG key you just downloaded.
One quick check: Are you definitely on Ubuntu 24.04? You can verify with lsb_release -a. If you are actually on 22.04, just swap the “24.04” and “noble” parts of the commands above with “22.04” and “jammy”.
(選填)安裝 SQL Server 命令列工具 (sqlcmd/bcp)
sudo ACCEPT_EULA=Y apt-get install -y mssql-tools18
echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc
source ~/.bashrc
第二步:安裝 Python 套件
在你的 Python 虛擬環境中安裝 pyodbc:
pip install pyodbc
錯誤訊息:
azureuser@vmptprodjpe001:~$ pip install pyodbc
error: externally-managed-environment
解決方法:建立虛擬環境
請按照以下步驟操作:
先確保系統有安裝建立虛擬環境的工具:
sudo apt update
sudo apt install python3-venv python3-full
在你的專案目錄下建立一個名為 venv 的虛擬環境:
python3 -m venv venv
啟動虛擬環境:
source venv/bin/activate
啟動後,你會發現指令列開頭多了 (venv) 的字樣,這時就可以放心安裝套件了:
pip install pyodbc
第三步:Python 程式碼範例與注意事項
由於 ODBC 18 預設強制加密,如果你的 Azure SQL 伺服器證書不是由受信任的授權單位簽發的(或者你在本地測試),你可能需要在連線字串中加入 TrustServerCertificate=yes。
import pyodbc
# 請替換成你的 Azure SQL 資訊
server = 'your_server.database.windows.net'
database = 'your_db'
username = 'your_username'
password = 'your_password'
# 注意 Driver 名稱必須精確匹配:{ODBC Driver 18 for SQL Server}
conn_str = (
f"DRIVER={{ODBC Driver 18 for SQL Server}};"
f"SERVER={server};"
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
"Encrypt=yes;"
"TrustServerCertificate=no;" # 若連線失敗可改為 yes 測試,但在正式環境建議保持 no
"Connection Timeout=30;"
)
try:
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("SELECT @@version;")
row = cursor.fetchone()
print(f"Connected! SQL Server Version: {row[0]}")
except Exception as e:
print(f"Error: {e}")
常見問題排除
- 找不到驅動程式:執行
odbcinst -q -d。你應該會看到[ODBC Driver 18 for SQL Server]。如果沒有,請確認第一步安裝是否成功。 - SSL/TLS 錯誤:Azure SQL 要求 TLS 1.2 以上版本。Ubuntu 20.04+ 通常預設支援,但如果你在連線時遇到證書驗證錯誤,請檢查 Azure SQL 的防火牆設定,並確認
TrustServerCertificate的設定。 - 權限問題:在 Azure VM 上,確保網路安全性群組 (NSG) 已允許 1433 埠通訊,且 Azure SQL 的防火牆已將該 VM 的公用 IP 加入白名單。
Error
W: OpenPGP signature verification failed: https://packages.microsoft.com/ubuntu/26.04/prod resolute InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EE4D7792F748182B
E: The repository 'https://packages.microsoft.com/ubuntu/26.04/prod resolute InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
看來在 Ubuntu 24.04 (Noble) 上,系統沒能正確識別或找到你剛才匯入的 Microsoft GPG 金鑰。這通常是因為金鑰存放路徑與來源清單(.list)中定義的路徑不一致導致的。
從你的錯誤訊息看,noble InRelease 找不到金鑰 EB3E94ADBE1229CF。
解決方案
請按照以下步驟重新匯入金鑰並修正路徑:
1. 下載並轉換金鑰格式
Ubuntu 24.04 偏好使用 .gpg 格式存放在 /usr/share/keyrings/。
# 下載並將金鑰轉換為 gpg 格式存放到指定位置
curl -sSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /usr/share/keyrings/microsoft-prod.gpg > /dev/null
2. 更新來源清單 (Source List)
確保你的 mssql-release.list 指向的是正確的金鑰路徑(剛才建立的那個):
echo "deb [arch=amd64,arm64,armhf signed-by=/usr/share/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/ubuntu/24.04/prod noble main" | sudo tee /etc/apt/sources.list.d/mssql-release.list
3. 再次執行安裝
現在更新索引,這一次應該不會報 GPG 錯誤了:
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18 unixodbc-dev
驗證安裝結果
安裝完成後,你可以執行這個指令確認驅動程式已經就緒:
odbcinst -q -d -n "ODBC Driver 18 for SQL Server"
如果出現驅動程式的路徑資訊,就代表你成功了!接著就可以繼續用 pip install pyodbc 進行 Python 開發。
要在 Ubuntu 終端機直接測試連線,我們通常會使用 sqlcmd (隨 mssql-tools18 安裝) 或者使用 isql (unixODBC 自帶工具)。
由於你安裝的是 ODBC Driver 18,請特別注意連線字串中的加密選項。
方法一:使用 isql 進行快速測試
isql 是 unixODBC 提供的工具,適合用來驗證驅動程式是否能正確與資料庫握手。
請在終端機輸入以下指令(將參數直接寫在連線字串中):
# -v 代表 verbose (詳細輸出),可以幫你判斷錯誤原因
# 注意:ODBC 18 預設強制加密,若伺服器憑證未經第三方認證,需加上 TrustServerCertificate=yes
isql -v -k "DRIVER={ODBC Driver 18 for SQL Server};SERVER=1.2.3.4,1433;DATABASE=YOUR_DB;UID=userid;PWD=userpwd;Encrypt=yes;TrustServerCertificate=yes"
- 如果成功,你會看到
Connected!提示。 - 輸入
quit即可結束連線。
方法二:使用 sqlcmd (Microsoft 官方工具)
如果你之前有安裝 mssql-tools18,這是最推薦的測試方式:
sqlcmd -S 1.2.3.4,1433 -d YOUR_DB -U userid -P 'userpwd' -C
- 參數
-C代表TrustServerCertificate(信任伺服器憑證)。 - 注意:如果密碼包含特殊字元,請用單引號
' '包起來。
疑難排解:連線失敗的常見原因
- Network Timeout (連線逾時):
- 檢查 Azure NSG:確保你的 Azure VM 出站規則 (Outbound) 允許 1433 埠。
- 檢查目標伺服器:1.2.x.x 的 IP,請確認該伺服器防火牆是否有將你的 Azure VM 公用 IP 加入白名單。
- SSL Provider 錯誤 (憑證問題):
- 這是 ODBC 18 最常見的問題。如果沒加
TrustServerCertificate=yes(或isql中的參數),連線會因為無法驗證憑證而中斷。
- 這是 ODBC 18 最常見的問題。如果沒加
- Login Failed:
- 請確認資料庫名稱 YOUR_DB 與帳密無誤。
Python 程式碼快速驗證
如果你已經進入了虛擬環境並安裝了 pyodbc,可以用這段代碼直接測試:
Python
import pyodbc
conn_str = (
"DRIVER={ODBC Driver 18 for SQL Server};"
"SERVER=1.2.3.4,1433;"
"DATABASE=YOUR_DB;"
"UID=userid;"
"PWD=userpwd;"
"Encrypt=yes;"
"TrustServerCertificate=yes;"
)
try:
with pyodbc.connect(conn_str, timeout=5) as conn:
print("連線成功!")
cursor = conn.cursor()
cursor.execute("SELECT TOP 1 name FROM sys.databases")
print(f"資料庫清單測試: {cursor.fetchone()}")
except Exception as e:
print(f"連線失敗原因: {e}")
你的連線測試結果出現什麼錯誤訊息嗎?