Python教程

[975]python requests实现HTTPS客户端的证书导入

本文主要是介绍[975]python requests实现HTTPS客户端的证书导入,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

最近需要测试一个HTTPS接口,基于CA证书、client key、 client 证书的ssl连接。

网上了解到的实现是用python+urllib,

import urllib.request

import ssl

if __name__ == '__main__':
    CA_FILE = "ca.crt"
    KEY_FILE = "client.key"
    CERT_FILE = "client.crt"

    context = ssl.SSLContext(ssl.PROTOCOL_TLS)
    context.check_hostname = False
    context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
    context.load_verify_locations(CA_FILE)
    context.verify_mode = ssl.CERT_REQUIRED
    try:
        # 通过request()方法创建一个请求:
        request = urllib.request.Request('https://127.0.0.1:5000/')
        res = urllib.request.urlopen(request, context=context)
        print(res.code)
        print(res.read().decode("utf-8"))
    except Exception as ex:
        print("Found Error in auth phase:%s" % str(ex))

想用python+requests实现,但requests没有context参数,requests官网描述如下,

image.png

image.png

用requests的cert+verify参数实现,连接成功,代码如下:

import requests

import ssl

if __name__ == '__main__':  
    try:
        # 通过request()方法创建一个请求:
         r=requests.get("https://127.0.0.1:5000/",cert=('client.crt','client.key'),verify='ca.crt')
    	print(r.status_code)
   	 	print(r.text)
    	print(r.headers)

    except Exception as ex:
        print("Found Error in auth phase:%s" % str(ex))

来源:https://blog.csdn.net/weixin_51380973/article/details/113864819

这篇关于[975]python requests实现HTTPS客户端的证书导入的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!