Python ssl.SSLError: WRONG_VERSION_NUMBER 完全指南:当 TLS 客户端连上了明文端口
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number 不是证书问题,也不是 Python 版本问题。它的含义非常具体:客户端在 TLS 握手第一步发出 ClientHello,对端返回的却根本不是 TLS 记录。最典型的场景是把 https:// 指向了一个跑明文 HTTP 的端口(8080、8443、8000 之类),服务器老老实实回了一行 HTTP/1.1 400 Bad Request,OpenSSL 把这行文本当成 TLS 记录头去解析,版本号字段自然对不上。本文给出可复制的诊断命令、端口协议对照表、各场景修复代码,以及真实报错的处置记录。
一、错误含义:TLS 握手收到的不是 TLS 记录
TLS 记录头固定 5 字节:内容类型 1 字节 + 版本 2 字节 + 长度 2 字节。正常握手时版本字段是 0x0301(TLS 1.0)到 0x0304(TLS 1.3)。当对端返回的是明文字节流,OpenSSL 仍按这个格式解析,版本号校验失败,于是抛出 WRONG_VERSION_NUMBER。
看对端返回的第一个字节,基本就能判定它是什么服务:
| 对端首字节 | 实际内容 | 典型端口 |
|---|---|---|
0x16 |
Handshake,真正的 TLS | 443、465、993、995、636 |
0x48(H) |
HTTP/1.1 400 Bad Request |
80、8080、8443(未开 ssl)、8000 |
0x53(S) |
SSH-2.0-OpenSSH_9.6 |
22 |
0x32(2) |
220 smtp.example.com ESMTP |
25、587 |
0x2a(*) |
Redis 协议响应 | 6379 |
完整的异常堆栈通常长这样。_ssl.c:1007 里的行号随 CPython 版本变化(3.9 常见 1129,3.10/3.11 常见 1007),它只是抛异常的那行 C 代码,不是错误原因:
Traceback (most recent call last):
File 'check.py', line 6, in <module>
r = requests.get('https://api.example.com:8080/health', timeout=5)
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=8080): Max retries exceeded with url: /health (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)')))
二、30 秒定位:这个端口到底是明文还是 TLS
不要猜,三条命令定生死。
# 1) 按明文 HTTP 试。有 HTTP 响应 = 它是 HTTP 端口
curl -sv --max-time 5 http://api.example.com:8080/health 2>&1 | head -20
# 2) 按 TLS 试。出现 wrong version number = 基本坐实
openssl s_client -connect api.example.com:8080 -servername api.example.com </dev/null 2>&1 | head -20
# 3) 直接看原始字节,不依赖任何客户端库
printf 'GET / HTTP/1.0rnrn' | timeout 5 nc api.example.com 8080 | head -c 64 | xxd
第 2 条的典型输出。注意 no peer certificate available 是握手从未建立的结果,不是证书缺失的原因:
$ openssl s_client -connect api.example.com:8080 -servername api.example.com </dev/null 2>&1 | head -20
CONNECTED(00000003)
40B7C1FF:error:0A00010B:SSL routines::wrong version number:ssl/record/ssl3_record.c:354:
---
no peer certificate available
---
No client certificate CA names sent
---
第 3 条直接把服务端回的明文抓出来,48 54 54 50 就是 HTTP:
$ printf 'GET / HTTP/1.0rnrn' | timeout 5 nc api.example.com 8080 | head -c 64 | xxd
00000000: 4854 5450 2f31 2e31 2034 3030 2042 6164 HTTP/1.1 400 Bad
00000010: 2052 6571 7565 7374 0d0a 5365 7276 6572 Request..Server
Python 侧同样可以自查,方便在 CI 或容器里跑:
python - <<'PY'
import socket
host, port = 'api.example.com', 8080
with socket.create_connection((host, port), timeout=5) as s:
s.sendall(b'GET / HTTP/1.0rnHost: ' + host.encode() + b'rnrn')
print(s.recv(64))
PY
# b'HTTP/1.1 400 Bad RequestrnServer: nginxrn...' <- 明文端口,别用 https://
如果能登到服务端,直接看监听配置更快:ss -tlnp | grep -E ':(443|8080|8443|8000)',以及 nginx -T | grep -n 'listen.*8443',listen 后面没有 ssl 关键字就是明文。
三、六种常见根因对照
| 场景 | 典型现象 | 验证方法 | 处理 |
|---|---|---|---|
| URL 用了 https,端口跑的是明文 HTTP | 首次请求立刻抛 SSLError | curl -I http://host:port 有响应 |
改 http://,或让服务端开 TLS |
| 反代把 443 转后端 80,客户端却直连了后端端口 | 只有内网访问才报错 | 比对 URL 与 nginx location |
直连网关,或后端也启用 TLS |
代理 scheme 写错(HTTPS_PROXY=https:// 指向明文代理) |
只有走代理时失败 | 报错里的 host 变成了代理地址 | 改成 http://proxy:3128 |
| 隐式 TLS 与 STARTTLS 用反(465/587、993/143、636/389) | smtplib/imaplib 报同款错误 | nc host 587 看到 220 banner |
587 用 SMTP + starttls() |
| 端口根本不是 HTTP 服务(SSH/Redis/MySQL) | TCP 连得上,握手失败 | nc 看 banner 首字节 |
换端口,或改用对应协议的客户端 |
| 中间设备回明文错误页(WAF、LB 健康检查失败、502 页) | 偶发,重试有时成功 | 抓包看握手阶段收到 HTTP 文本 | 修后端健康检查,统一 TLS 终止点 |
四、端口与协议对照表
把这张表贴在工位上,能省掉一半排查时间。8443 没有标准含义,必须实测。
| 端口 | 常见服务 | 是否 TLS | 对端首字节 | Python 正确用法 |
|---|---|---|---|---|
| 443 | HTTPS | 是 | 0x16 |
requests.get('https://...') |
| 80 | HTTP | 否 | H | http:// |
| 8080 | HTTP 备用端口 | 否(绝大多数) | H | http:// |
| 8443 | Tomcat HTTPS 或第二个 HTTP 端口 | 视配置 | 0x16 或 H |
先用 openssl s_client 确认 |
| 8000 / 8888 | 开发服务器 | 否 | H | http:// |
| 465 | SMTPS(隐式 TLS) | 是 | 0x16 |
smtplib.SMTP_SSL |
| 587 | SMTP + STARTTLS | 明文起步 | 2 | smtplib.SMTP + starttls() |
| 25 | SMTP 明文 | 否 | 2 | 不推荐直接做 TLS |
| 993 | IMAPS | 是 | 0x16 |
imaplib.IMAP4_SSL |
| 143 | IMAP + STARTTLS | 明文起步 | * | imaplib.IMAP4 + starttls() |
| 995 | POP3S | 是 | 0x16 |
poplib.POP3_SSL |
| 110 | POP3 明文 | 否 | +OK | poplib.POP3 + stls() |
| 636 | LDAPS | 是 | 0x16 |
ldap3 的 use_ssl=True |
| 389 | LDAP + STARTTLS | 明文起步 | 0x30 |
ldap3 start_tls() |
| 6379 | Redis | 否(默认) | * | redis-py 的 ssl=True 才加密 |
| 22 | SSH | 否 | S | paramiko,与 TLS 无关 |
五、修复:按场景给出可执行方案
5.1 只是 URL 写错了(八成的情况)
import requests
# 错误:https 指向了跑 HTTP 的 8080
# requests.get('https://api.example.com:8080/health')
# 正确:scheme 与端口对齐
r = requests.get('http://api.example.com:8080/health', timeout=10)
print(r.status_code, r.text[:200])
如果对端是你自己维护的服务,更推荐在 8443 上真正启用 TLS,而不是把客户端降级成 http。
5.2 在 nginx 的 8443 上真正开启 TLS
# 改之前:只有端口没有 ssl,这就是明文 HTTP
# server { listen 8443; ... }
server {
listen 8443 ssl;
server_name api.example.com;
ssl_certificate /etc/nginx/certs/api.crt;
ssl_certificate_key /etc/nginx/certs/api.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
}
nginx -t && nginx -s reload
openssl s_client -connect api.example.com:8443 -servername api.example.com </dev/null 2>&1 | openssl x509 -noout -subject -dates
5.3 自签证书或内网 CA:不要用 verify=False 糊过去
import requests
r = requests.get(
'https://api.internal:8443/health',
verify='/etc/ssl/certs/internal-ca.pem', # 指向企业 CA 或完整证书链
timeout=10,
)
print(r.status_code)
也可以对整进程生效:export REQUESTS_CA_BUNDLE=/etc/ssl/certs/internal-ca.pem。只有本地一次性调试才考虑 verify=False 配合 urllib3.disable_warnings()。
5.4 裸 socket 与 http.client 场景
import http.client, socket, ssl
# 明文
conn = http.client.HTTPConnection('api.example.com', 8080, timeout=10)
# TLS:wrap_socket 必须带 server_hostname,否则 SNI 与主机名校验都会出问题
ctx = ssl.create_default_context()
with socket.create_connection(('api.example.com', 8443), timeout=10) as raw:
with ctx.wrap_socket(raw, server_hostname='api.example.com') as s:
print(s.version()) # TLSv1.3
print(s.getpeercert()['subject'])
5.5 STARTTLS 类协议:先明文握手再升级
import smtplib, ssl
ctx = ssl.create_default_context()
# 587:明文连上,再 STARTTLS 升级(用 SMTP_SSL 连 587 就是 WRONG_VERSION_NUMBER)
with smtplib.SMTP('smtp.example.com', 587, timeout=10) as s:
s.ehlo()
s.starttls(context=ctx)
s.ehlo()
s.login('user', 'pass')
s.sendmail('from@example.com', ['to@example.com'], 'Subject: hirnrnbody')
# 465:隐式 TLS,连接即加密
with smtplib.SMTP_SSL('smtp.example.com', 465, context=ctx, timeout=10) as s:
s.login('user', 'pass')
六、代理:HTTPS_PROXY、CONNECT 与 trust_env
走代理访问 https 时,客户端先发 CONNECT host:443 HTTP/1.1 让代理开隧道,隧道建好后才开始 TLS。代理 URL 的 scheme 描述的是“怎么跟代理说话”,不是目标站点:代理本身是明文 HTTP,就必须写 http://。
# 错误:把明文 HTTP 代理写成 https://,客户端会先和代理做 TLS,代理回明文 -> WRONG_VERSION_NUMBER
export HTTPS_PROXY=https://proxy.corp.example:3128
# 正确
export HTTPS_PROXY=http://proxy.corp.example:3128
export HTTP_PROXY=http://proxy.corp.example:3128
export NO_PROXY=localhost,127.0.0.1,.internal.example
验证代理链路是否支持 CONNECT:
curl -v -x http://proxy.corp.example:3128 https://api.example.com/health 2>&1 | grep -E 'CONNECT|HTTP/1.1|wrong version'
# 正常应看到:
# > CONNECT api.example.com:443 HTTP/1.1
# < HTTP/1.1 200 Connection established
Python 里临时绕开环境变量里的代理,或显式指定代理:
import requests
s = requests.Session()
s.trust_env = False # 忽略 HTTPS_PROXY / HTTP_PROXY / .netrc
r = s.get('https://api.example.com/health',
verify='/etc/ssl/certs/internal-ca.pem', timeout=10)
# 或显式指定(两个 key 都指向 HTTP 代理)
r = requests.get(
'https://api.example.com/health',
proxies={'http': 'http://proxy.corp.example:3128',
'https': 'http://proxy.corp.example:3128'},
timeout=10,
)
排查时先看环境:env | grep -i proxy。很多 CI 镜像里预置了 HTTPS_PROXY,本地跑得好好的代码一进容器就炸,原因往往就在这里。
七、故障排查实录:真实报错与处置
7.1 requests 直连 8080
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.example.com', port=8080): Max retries exceeded with url: /health (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)')))
# 处置:把 URL 改成 http://api.example.com:8080/health
7.2 curl 报同样的错,说明与 Python 无关
$ curl -I https://api.example.com:8443/
curl: (35) error:0A00010B:SSL routines::wrong version number
# 说明:curl 用同一套 OpenSSL,报错一致,问题在服务端端口协议
# 交叉验证:curl -I http://api.example.com:8443/ 能出 HTTP/1.1 200 -> 该端口是明文
7.3 openssl s_client 报错且看不到证书
40B7C1FF:error:0A00010B:SSL routines::wrong version number:ssl/record/ssl3_record.c:354:
---
no peer certificate available
---
No client certificate CA names sent
# 'no peer certificate available' 是握手失败的结果,不是证书缺失的原因
# 如果这里能看到证书,问题才可能落在 CERTIFICATE_VERIFY_FAILED 上
7.4 smtplib 用 SMTP_SSL 连 587
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)
# 587 是明文起步 + STARTTLS;隐式 TLS 只有 465
# 处置:smtplib.SMTP(host, 587) 然后 starttls()
7.5 代理 scheme 写错,报错里的 host 变成了代理地址
# 在 export HTTPS_PROXY=https://proxy.corp.example:3128 之后:
requests.exceptions.SSLError: HTTPSConnectionPool(host='proxy.corp.example', port=3128): Max retries exceeded with url: /health (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)')))
# 关键信号:host 是代理而不是目标站点,说明客户端在跟代理做 TLS
# 处置:export HTTPS_PROXY=http://proxy.corp.example:3128
7.6 连到了 SSH 或 Redis 端口
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)
# printf '' | nc host 22 -> SSH-2.0-OpenSSH_9.6
# printf '' | nc host 6379 -> -NOAUTH Authentication required.
# 处置:端口写错了;SSH 用 paramiko,Redis 用 redis-py
7.7 网关回 502 明文页导致的偶发失败
# 现象:偶发,重试有时成功;抓包看到握手阶段收到 'HTTP/1.1 502 Bad Gateway'
# 原因:LB 健康检查失败后直接回明文错误页,客户端把它当 TLS 记录解析
# 处置:修后端健康检查;统一由网关做 TLS 终止,并保证错误页也走 TLS
7.8 httpx / aiohttp 报同款错误
httpx.ConnectError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1007)
aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host api.example.com:8080 ssl:default
# 处置同上:scheme 与端口对齐,与是否异步框架无关
八、FAQ
Q1:加 verify=False 能解决吗?
不能。verify 只控制“拿到证书后要不要校验”,而 WRONG_VERSION_NUMBER 发生在拿到证书之前。证书类问题报的是 [SSL: CERTIFICATE_VERIFY_FAILED]。
Q2:升级 Python 或 OpenSSL 有用吗?
基本没用。_ssl.c:1129 或 _ssl.c:1007 只是 CPython 里抛异常的那一行 C 代码,随版本变化,不是错误原因。协议不对,换哪个版本都一样。
Q3:浏览器能打开,Python 打不开,为什么?
浏览器会把 https://host 默认补成 443,而你的代码里显式写了 8080 或 8443;浏览器还走系统代理与 HSTS,Python 走的是自己的环境变量与 CA。先对比两边的完整 URL 和端口,再用 curl 交叉验证。
Q4:curl 成功但 requests 失败?
常见两个差异:一是代理环境变量,curl 认小写 http_proxy,requests 通过 urllib 同时读大小写,容易一边生效一边不生效;二是 CA 来源,requests 用 certifi,可用 REQUESTS_CA_BUNDLE 覆盖,curl 用系统 CA。
Q5:8443 到底是不是 HTTPS?
没有标准答案。8443 只是“备用 Web 端口”,Tomcat、部分网关默认在上面跑 HTTPS,但更多自建服务把它当第二个 HTTP 端口。唯一可靠的判断方式是 openssl s_client 或直接看原始字节。
Q6:能不能在代码里自动降级,先试 https 再试 http?
不建议。静默降级会把配置错误藏起来,还可能把凭据发到明文通道。正确做法是让配置显式声明 scheme,启动时做一次健康检查并快速失败。
Q7:Docker / K8s 里为什么更容易踩?
端口映射会改变语义:docker run -p 8443:80 让宿主机的 8443 变成明文 HTTP;Ingress 做 TLS 终止时,Service 后端通常仍是 80 明文。访问入口用 https,访问后端必须用 http。
Q8:有没有一句话的排查口诀?
“握手报版本,先看端口协议”。看到 WRONG_VERSION_NUMBER,第一反应永远是确认对端端口跑的是不是 TLS,而不是去翻证书和依赖版本。