背景


以一个python的request的demo为例,访问双向认证的网站并打印其首页文本信息:

1
2
3
4
5
import requests

url = "https://pro6.aishu.cn"
response = requests.get(url)
print(response.text.encode("GBK", "ignore"))

会报如下错误:

1
2
3
4
5
6
7
8
9
C:\Users\liu.ziyi\AppData\Local\Programs\Python\Python38\python.exe E:/Python/httpRunnerDemo/kom/kom_session.py
<html>
<head><title>400 No required SSL certificate was sent</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<center>No required SSL certificate was sent</center>
<hr><center>nginx</center>
</body>
...

双向认证的网站,即需要预先在本地安装对应的客户端证书,在访问该网站时,选择该证书才可访问该网站。

对于使用python发送request请求而言,这个过程也不例外。

根据.pfx证书文件使用requests-pkcs12


安装requests-pkcs12模块,可参考requests-pkcs12官方介绍

1
pip install requests_pkcs12

使用requests_pkcs12python代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
import requests
from requests_pkcs12 import Pkcs12Adapter

session = requests.session()
url = "https://pro6.aishu.cn"

# 指定双向认证网站的pfx证书文件,并附带证书的密码
session.mount(url, Pkcs12Adapter(pkcs12_filename='client.pfx', pkcs12_password='xxx'))

# 使用session调用get/post方法
response = session.get(url)
print(response.status_code)

再次执行即可。

根据.crt和.key证书文件使用requests


根据pfx证书文件生成.crt、.key文件:

1
2
3
4
5
6
7
8
9
10
[root@centos7 cert]# openssl pkcs12 -in client.pfx -nocerts -nodes -out example.key
Enter Import Password:
MAC verified OK

[root@centos7 cert]# openssl pkcs12 -in client.pfx -clcerts -nokeys -out example.crt
Enter Import Password:
MAC verified OK

[root@centos7 cert]# ls
client.pfx example.crt example.key

使用request发送证书的python代码如下:

1
2
3
4
5
import requests

url = "https://pro6.aishu.cn"
response = requests.get(url, cert=('example.crt', 'example.key'))
print(response.status_code)