在 Ubuntu 上使用 msodbcsql17 (Microsoft ODBC Driver 17 for SQL Server) 连接旧版本的 SQL Server 2012,通常会遇到加密协议(SSL/TLS)不兼容的问题。SQL Server 2012 默认使用旧的 TLS 版本,而现代的 Linux 驱动程序要求更高版本的 TLS
菜单
一、补全基础工具并安装 ODBC 17
# 1. 补全基础工具
apt update
apt install -y lsb-release curl gnupg2 apt-transport-https
# 2. 清理并重新添加微软源(强制用 22.04,兼容性最好)
rm -f /etc/apt/sources.list.d/mssql-release.list
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
echo "deb [arch=amd64] https://packages.microsoft.com/ubuntu/22.04/prod jammy main" > /etc/apt/sources.list.d/mssql-release.list
# 3. 安装 ODBC 17
apt update
ACCEPT_EULA=Y apt install -y msodbcsql17 unixodbc-dev
# 安装sqlcmd和bcp (可选,用于测试)
apt-get install mssql-tools
二、测试链接
1. 在当前目录创建一个专门用于 SQL 连接的配置文件
cat > /tmp/openssl_legacy.cnf << 'EOF'
openssl_conf = openssl_init
[openssl_init]
ssl_conf = ssl_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
MinProtocol = None
MaxProtocol = None
CipherString = DEFAULT@SECLEVEL=0
EOF
2. 使用环境变量临时加载这个配置并测试
在运行 sqlcmd
# 临时生效(仅对当前终端有效)
export OPENSSL_CONF=/tmp/openssl_legacy.cnf
# 再次测试 sqlcmd
/opt/mssql-tools/bin/sqlcmd -S 120.77.47.174,14333 -U xxx -P xxx -d nccdb -C
三、设置配置文件
3.1 1. 确认我们的 legacy 配置文件内容是完整的
cat > /etc/ssl/openssl_legacy.cnf << 'EOF'
openssl_conf = openssl_init
[openssl_init]
ssl_conf = ssl_sect
[ssl_sect]
system_default = system_default_sect
[system_default_sect]
MinProtocol = None
MaxProtocol = None
CipherString = DEFAULT@SECLEVEL=0
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
string_mask = utf8only
default_md = sha256
x509_extensions = v3_ca
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
stateOrProvinceName = State or Province Name
localityName = Locality Name
0.organizationName = Organization Name
organizationalUnitName = Organizational Unit Name
commonName = Common Name
emailAddress = Email Address
[ v3_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = CA:true
EOF
2. 直接强制替换系统主配置文件
# 备份原文件(以防万一)
cp /etc/ssl/openssl.cnf /etc/ssl/openssl.cnf.final_backup
# 直接覆盖!
cp /etc/ssl/openssl_legacy.cnf /etc/ssl/openssl.cnf
四、创建测试文件
在 /app 目录下创建 test_pyodbc.py:
import os
import pyodbc
# 填入你的配置
config = {
'server': '120.xx.xx.xx',
'port': xxxx,
'user': 'xxxx',
'password': 'xxxxxx',
'database': 'xxxx'
}
server = f"{config['server']},{config['port']}"
conn_str = (
"DRIVER={ODBC Driver 17 for SQL Server};"
f"SERVER={server};"
f"UID={config['user']};"
f"PWD={config['password']};"
f"DATABASE={config['database']};"
"TrustServerCertificate=yes;"
)
print("正在尝试连接 SQL Server...")
try:
conn = pyodbc.connect(conn_str)
print("✅ Python 连接成功!")
cursor = conn.cursor()
cursor.execute("SELECT GETDATE() AS CurrentTime, DB_NAME() AS CurrentDB")
row = cursor.fetchone()
print(f"当前时间: {row.CurrentTime}")
print(f"当前数据库: {row.CurrentDB}")
conn.close()
except Exception as e:
print(f"❌ 连接失败: {e}")
运行脚本
python3 test_pyodbc.py
