如何与python建立安全连接?

时间:2017-08-19 06:16:58

标签: python python-3.x ssl https

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

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

如您所见,此类获取文件路径并正常工作。 但我需要提供这些文件的内容。因为我想把crt文件和pem文件的内容放入DB。原因是文件路径可能会发生变化...... 所以我试过这个:

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的源代码?!

1 个答案:

答案 0 :(得分:0)

可以修改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)
# ...