python - 如何与 python 建立安全连接?

标签 python python-3.x ssl https

我正在使用 python3。我需要使用证书文件来建立安全连接。 在这种情况下,我使用了 http.client 中的 Httpsconnection 类... 此类获取证书文件路径并使用它。像这样:

 import http.client
 client=http.client.HTTPSConnection\
 ("epp.nic.ir",key_file="filepath\\nic.pem",cert_file="filepath\\nic.crt")

如您所见,此类获取文件路径并正常工作。 但我需要提供这些文件的内容。因为我想把crt文件和pem文件的内容放到数据库中。原因是也许文件路径改变了...... 所以我尝试了这个:

import http.client
import base64

cert = b'''
content of cert file
'''
pem = b'''
content of pem file
'''
client=http.client.HTTPSConnection("epp.nic.ir" ,pem, cert)

正如预期的那样,我得到了这个错误:

TypeError: certfile should be a valid filesystem path

有没有办法让这个类获取文件内容而不是文件路径?! 或者是否可以为此目的更改 http 的源代码?!

最佳答案

可以修改Python源码,但不推荐这种方式,肯定会带来可移植性、可维护性等问题。

  • 考虑到您想要更新 Python 版本,您必须在每次更新时应用您的修改。
  • 假设您想在另一台机器上运行您的代码,同样的问题。

除了修改源代码,还有更好更可取的方法:扩展API。

您可以继承现有的 HTTPSConnection 类,并通过您自己的实现覆盖其构造方法。

有很多方法可以满足您的需求。

这是一个可能的子类化解决方案:

import http.client
import tempfile

class MyHTTPSConnection(http.client.HTTPSConnection):
    """HTTPSConnection with key and cert files passed as contents rather than file names"""

    def __init__(self, host, key_content=None, cert_content=None, **kwargs):
        # additional parameters are also optional so that
        # so that this class can be used with or without cert/key files
        # as a replacement of standard HTTPSConnection
        self.key_file = None
        self.cert_file = None

        # here we write the content of cert & pem into a temporary file
        # delete=False keeps the file in the file system
        # but, this time we need to remove it manually when we are done
        if key_content:
            self.key_file = tempfile.NamedTemporaryFile(delete=False)
            self.key_file.write(key_content)
            self.key_file.close()
            # NamedTemporaryFile object provides 'name' attribute
            # which is a valid file name in the file system
            # so we can use those file names to initiate the actual HTTPSConnection
            kwargs['key_file'] = self.key_file.name

        # same as above but this time for cert content and cert file
        if cert_content:
            self.cert_file = tempfile.NamedTemporaryFile(delete=False)
            self.cert_file.write(cert_content)
            self.cert_file.close()
            kwargs['cert_file'] = self.cert_file.name


        # initialize super class with host and keyword arguments
        super().__init__(host, **kwargs)

    def clean(self):
        # remove temp files from the file system
        # you need to decide when to call this method
        os.unlink(self.cert_file.name)
        os.unlink(self.pem_file.name)

host = "epp.nic.ir"
key_content = b'''content of key file'''
cert_content = b'''content of cert file'''

client = MyHTTPSConnection(host, key_content=key_content, cert_content=cert_content)
# ...

关于python - 如何与 python 建立安全连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45768351/

相关文章:

python - 数据点颜色从预先指定的点呈放射状变化

python-3.x - 调度程序和执行程序的 APScheduler 记录器

amazon-web-services - 将证书/ key 上传到 AWS 负载均衡器

.net - 使用 IronPython 强制 SSL 协议(protocol) TLSv1.2

python - 在python中调用没有WSDL的soap API

python - TypeError : request() got an unexpected keyword argument 'header' - when i use header, 403 错误 - 没有 header

python - py2neo SocketError : Connection refused, 但curl可以工作

python - 异步中的奇怪断言错误

python-3.x - 分发包时处理 API key 的 pythonic 方式是什么?

ssl - 使用 Https 和第二个有效证书的中间人攻击