Sqlcmd: Error: Microsoft SQL Native Client:
An error has occurred while establishing a connection to the server.
When connecting to SQL Server 2005, this failure may be caused by the fact that
under the default settings SQL Server does not allow remote connections.
預設 SQL Server 2005 Express / Developer Edition **關閉遠端連線**、**停用 Browser 服務**、**防火牆封鎖 1433/1434 埠**。
必要性: 用戶端以執行個體名稱連線 (如 `Server\SQLEXPRESS`) 且未指定 TCP 埠時,Browser 服務負責解析執行個體對應的動態埠號 (UDP 1434)。
⚠️ 安全性考量: Browser 服務會公開伺服器上所有執行個體名稱與連線資訊。若環境高敏感,建議:
① 關閉 Browser,改用固定 TCP 埠 (下節設定) 直連;
② 防火牆封鎖 UDP 1434 僅允許受信任子網。
-- 本機測試
sqlcmd -S .\SQLEXPRESS -E -Q "SELECT @@VERSION"
-- 遠端測試 (IP + 執行個體)
sqlcmd -S 192.168.1.100\SQLEXPRESS -U login -P pwd -Q "SELECT DB_NAME()"
-- 遠端測試 (IP + 固定埠)
sqlcmd -S 192.168.1.100,2433 -U login -P pwd -Q "SELECT DB_NAME()"
| 現象 | 可能原因 | 排查步驟 |
|---|---|---|
| 本機連得上、遠端連不上 | 防火牆封鎖、TCP/IP 未啟用、Browser 未啟動 | telnet IP 1433;檢查錯誤日誌 `Login failed`/`Connection timeout` |
| 命名執行個體連不上、預設實例正常 | Browser 服務未啟動、UDP 1434 被封鎖 | 啟用 Browser 或改用固定埠直連 |
| 連線後隨即斷開 | 強制加密、憑證不信任、登入觸發器封鎖 | 檢查 `Force Encryption` 設定、Errorlog 17836/18456 |
| Windows 驗證失敗 (雙躍點) | Kerberos 委派未設定 (SPN) | 設定 SPN:`setspn -A MSSQLSvc/Host:Port Domain\ServiceAccount` |