Python爬虫在Linux中如何导入客户端证书?
做一个京东的商家后台管理系统的爬虫,第一次登录需要接收手机验证码后下载证书,这个证书是用于校验客户端的,在 Windows 下安装成功,也可以在证书管理那里导出,但是如何安装到 linux 上呢?现在登录程序都做好了,就差导入这个客户端证书到 linux 中了。查到说是添加到 /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem ,试了,不好使。系统是 centos7,望各位大佬不吝赐教。
Python爬虫在Linux中如何导入客户端证书?
4 回复
<img src=“http://thyrsi.com/t6/371/1537189468x-1922733133.png” />
在Linux上给Python爬虫加客户端证书,直接用requests库的cert参数就行。
关键代码:
import requests
# 如果你的证书是分开的
response = requests.get('https://client-auth-required.com',
cert=('/path/to/client.crt', '/path/to/client.key'))
# 如果你的证书是PEM格式(证书和私钥在一个文件里)
response = requests.get('https://client-auth-required.com',
cert='/path/to/client.pem')
完整示例:
import requests
from requests.adapters import HTTPAdapter
from urllib3.poolmanager import PoolManager
import ssl
class SSLAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile='/path/to/client.crt',
keyfile='/path/to/client.key')
kwargs['ssl_context'] = context
return super().init_poolmanager(*args, **kwargs)
# 使用自定义适配器
session = requests.Session()
session.mount('https://', SSLAdapter())
response = session.get('https://client-auth-required.com')
如果是httpx库(异步场景):
import httpx
async with httpx.AsyncClient(
cert=('/path/to/client.crt', '/path/to/client.key')
) as client:
response = await client.get('https://client-auth-required.com')
注意点:
- 证书文件路径要用绝对路径
- 确保私钥文件有正确的权限(比如
chmod 600 client.key) - 如果服务器需要中间证书,得把证书链拼接到一起
一句话建议: 用requests的cert参数最直接,复杂场景用自定义SSL适配器。
rhel 安装自制证书
cp *.crt /etc/pki/ca-trust/source/anchors/
update-ca-trust
直接在爬虫请求代码里加上也可以吧。

