Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何验证服务器';python中的ssl证书?_Python_Ssl_Certificate_Verify - Fatal编程技术网

如何验证服务器';python中的ssl证书?

如何验证服务器';python中的ssl证书?,python,ssl,certificate,verify,Python,Ssl,Certificate,Verify,我已将我的服务器配置为仅为https服务,以创建自签名证书。我有一个客户端,我必须验证服务器的证书,然后从服务器下载一个文件 如何在客户端中实现验证?有代码示例吗 我的问题与此类似: 尽管解释得很好,但我没有找到任何帮助 到目前为止,我在代码中创建了一个目录,然后用urllib2下载该文件: [...] #imports def dir_creation(path): try: os.makedirs(path) except OSError as exception: if

我已将我的服务器配置为仅为https服务,以创建自签名证书。我有一个客户端,我必须验证服务器的证书,然后从服务器下载一个文件

如何在客户端中实现验证?有代码示例吗

我的问题与此类似: 尽管解释得很好,但我没有找到任何帮助

到目前为止,我在代码中创建了一个目录,然后用urllib2下载该文件:

[...] #imports

def dir_creation(path):
try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise


def file_download(url):
ver_file = urllib2.urlopen(url)
data = ver_file.read()
with open(local_filename, "wb") as code:
    code.write(data)

dir_creation(path)
file_download(url)

与其将服务器配置为提供自签名证书,不如使用自签名证书作为证书颁发机构来签署服务器证书。(如何做到这一点超出了您的问题范围,但我相信您可以在堆栈溢出或其他方面找到帮助。)

现在,您必须将客户端配置为信任您的证书颁发机构。在python(2.7.9或更高版本)中,可以使用
ssl
模块执行此操作:

import ssl

...  # create socket

ctx = ssl.create_default_context(cafile=path_to_ca_certificate)
sslsock = ctx.wrap_socket(sock)
然后,您可以在安全套接字上传输和读取数据。有关更多说明,请参阅

urllib2
API更简单:

import urllib2

resp = urllib2.urlopen(url, cafile=path_to_ca_certificate)
resp_body = resp.read()
如果您希望使用请求,根据文档,您可以将其作为
verify
参数的参数:

resp = requests.get(url, verify=path_to_ca_certificate)

我已经用我的代码更新了这个问题,我已经使用urllib2方法了。你说它可以验证证书?我无法获取此参数:cafile=path\u to\u ca\u certificate。这是客户的证书吗?您能详细说明一下吗?它是在Python2.7.9中发布的,它对
ssl
模块进行了后端口改进。如果您使用的是Python2,那么应该升级到2.7.9。