openssl s_client 是调试 SSL/TLS 连接的利器。它可以建立到远程服务器的 SSL/TLS 连接,显示证书链、协议版本、加密套件等详细信息,是排查 HTTPS 问题的必备工具。
基本用法#
连接 HTTPS 服务器#
1
|
openssl s_client -connect example.com:443
|
执行后会显示完整的 SSL/TLS 握手信息,包括证书链、协议版本、加密套件等。
指定 SNI(Server Name Indication)#
对于共享 IP 的虚拟主机,必须指定 SNI:
1
|
openssl s_client -connect example.com:443 -servername example.com
|
不指定 SNI 时,服务器可能返回默认证书,导致证书验证失败。
常用场景#
1. 查看证书信息#
提取服务器证书并查看详情:
1
2
3
4
5
|
# 获取证书
echo | openssl s_client -connect www.baidu.com:443 -servername www.baidu.com 2>/dev/null | openssl x509 -noout -text
# 只看有效期
echo | openssl s_client -connect www.baidu.com:443 -servername www.baidu.com 2>/dev/null | openssl x509 -noout -dates
|
输出示例:
1
2
|
notBefore=Jul 9 07:01:02 2025 GMT
notAfter=Aug 10 07:01:01 2026 GMT
|
2. 检查协议版本#
查看实际使用的 TLS 版本:
1
|
echo | openssl s_client -connect www.baidu.com:443 -servername www.baidu.com 2>/dev/null | grep "Protocol"
|
输出:
3. 查看加密套件#
1
|
echo | openssl s_client -connect www.baidu.com:443 -servername www.baidu.com 2>/dev/null | grep "Cipher"
|
输出:
1
|
Cipher : ECDHE-RSA-AES128-GCM-SHA256
|
4. 测试特定 TLS 版本#
强制使用 TLS 1.2:
1
|
openssl s_client -connect example.com:443 -tls1_2
|
强制使用 TLS 1.3:
1
|
openssl s_client -connect example.com:443 -tls1_3
|
如果服务器不支持指定版本,连接会失败。
5. 验证证书链#
显示完整证书链:
1
|
echo | openssl s_client -connect example.com:443 -showcerts 2>/dev/null
|
-showcerts 参数会打印服务器发送的所有证书,便于排查证书链问题。
6. 测试 SMTP STARTTLS#
1
|
openssl s_client -connect smtp.example.com:587 -starttls smtp
|
7. 查看 OCSP 响应#
1
|
openssl s_client -connect example.com:443 -status 2>/dev/null | grep -A 20 "OCSP response"
|
实用技巧#
静默模式#
使用 -quiet 减少输出:
1
|
echo | openssl s_client -connect example.com:443 -quiet 2>/dev/null
|
发送 HTTP 请求#
连接后可以手动输入 HTTP 请求:
1
2
3
4
5
6
7
|
openssl s_client -connect example.com:443 -quiet
# 然后输入:
GET / HTTP/1.1
Host: example.com
Connection: close
# 注意:最后需要两个空行
|
检查会话复用#
1
|
openssl s_client -connect example.com:443 -reconnect 2>/dev/null | grep -E "reused|new"
|
常见问题排查#
| 问题 |
排查方法 |
| 证书过期 |
查看 -dates 输出 |
| 协议不匹配 |
用 -tls1_2 / -tls1_3 测试 |
| SNI 问题 |
添加 -servername 参数 |
| 证书链不完整 |
用 -showcerts 查看链 |
| 加密套件弱 |
查看 Cipher 输出 |
openssl s_client 是 SSL/TLS 调试的瑞士军刀,无需安装额外工具,OpenSSL 自带。掌握它的常用参数,可以快速排查 HTTPS 连接问题。