You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL2 Ubuntu环境下pyodbc.connect连接SQL Server失败,Windows正常如何解决?

WSL2(Ubuntu)连接Windows SQL Server失败的解决方法

问题描述

使用以下代码连接SQL Server:

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=127.0.0.1;DATABASE=mydb;UID=user;PWD=pass')

该代码在Windows环境的Jupyter Notebook中正常运行,但在WSL2(Ubuntu)环境下连接同一SQL Server时,出现登录超时错误:

('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

使用sqlcmd直接连接Windows端SQL Server(IP为172.27.224.1)时,返回SSL协议不支持错误:

(rapids-24.02) user@DESKTOP:~$ sqlcmd -S 172.27.224.1 -U user -P pass

Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : SSL Provider: [error:0A000102:SSL routines::unsupported protocol].
Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Client unable to establish connection.

注:WSL2通过nc和telnet测试1433端口均能连通:

nc -zv 172.27.224.1 1433

Connection to 172.27.224.1 1433 port [tcp/ms-sql-s] succeeded!

telnet 172.27.224.1 1433

Trying 172.27.224.1...
Connected to 172.27.224.1.
Escape character is '^]'.

修复步骤

1. 绕过SSL验证(最快解决方法)

错误核心是SSL协议版本不兼容,直接在连接字符串中禁用加密:

  • 修改pyodbc连接代码:
    conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=172.27.224.1;DATABASE=mydb;UID=user;PWD=pass;Encrypt=no')
    
  • sqlcmd命令添加-N no参数:
    sqlcmd -S 172.27.224.1 -U user -P pass -N no
    

2. 更新WSL2的ODBC驱动和OpenSSL

旧版本的驱动或OpenSSL可能不支持SQL Server的SSL协议:

# 更新ODBC Driver 17
sudo apt update && sudo apt install --only-upgrade msodbcsql17
# 更新OpenSSL
sudo apt update && sudo apt install --only-upgrade openssl

3. 检查Windows端SQL Server配置

  • 打开SQL Server配置管理器,确保TCP/IP协议已启用
  • 若SQL Server启用了SSL,确认其使用的TLS版本(如TLS 1.2)在WSL2的OpenSSL中被支持;可临时禁用SSL测试连接
  • 检查Windows防火墙,允许WSL2子网的1433端口入站流量
  • 确认SQL Server账户user拥有远程连接权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:06:32