前言

当 HTTPS 网站出现连接问题时,浏览器只显示模糊的错误信息。OpenSSL 的 s_client 命令是排查这类问题的利器,能看到完整的 TLS 握手过程和证书详情。

基本用法

连接 HTTPS 服务器并查看证书:

1
echo | openssl s_client -connect example.com:443

这会输出完整的 TLS 握手信息和证书链。

常用排查场景

1. 查看证书主体和有效期

1
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -subject -dates

输出示例:

1
2
3
subject=CN = example.com
notBefore=Jan  1 00:00:00 2025 GMT
notAfter=Jan  1 00:00:00 2026 GMT

2. 检查证书链完整性

1
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | grep -E "depth|subject|issuer"

会显示证书链的每一层,帮助定位中间证书缺失问题。

3. 测试 TLS 版本

测试服务器是否支持 TLS 1.2:

1
echo | openssl s_client -connect example.com:443 -tls1_2 2>&1 | grep "Protocol"

测试 TLS 1.3:

1
echo | openssl s_client -connect example.com:443 -tls1_3 2>&1 | grep "Protocol"

4. 查看协商的加密套件

1
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | grep "Cipher"

输出类似:

1
Cipher    : TLS_AES_256_GCM_SHA384

5. 验证证书有效性

使用系统 CA 证书验证:

1
echo | openssl s_client -connect example.com:443 -servername example.com 2>&1 | grep "Verify return"

输出 Verify return code: 0 (ok) 表示证书有效。

6. 显示完整证书内容

1
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -text

包含证书的所有字段:主题、颁发者、有效期、SAN 扩展、公钥信息等。

SNI 支持

现代服务器通常使用 SNI(Server Name Indication),必须加 -servername 参数:

1
echo | openssl s_client -connect 192.168.1.100:443 -servername example.com

否则可能返回默认证书而非目标域名的证书。

超时设置

连接慢或无响应时,设置超时:

1
echo | timeout 5 openssl s_client -connect example.com:443

小结

场景 命令
查看证书信息 s_client ... | openssl x509 -noout -text
检查有效期 s_client ... | openssl x509 -noout -dates
测试 TLS 版本 s_client -tls1_2-tls1_3
查看加密套件 s_client ... | grep Cipher
验证证书链 `s_client … | grep -E “depth

s_client 是 HTTPS 排查的瑞士军刀,掌握它能快速定位证书、协议、加密套件等各类问题。