尝试在Jupyter笔记本中处理我公司的SSL证书

时间:2018-12-17 10:07:16

标签: python ssl

在我的公司与pytorch进行深度学习时,我的公司的IT安全系统目前存在问题,尽管它们为我提供了我合并为.pem文件的证书文件

我没有使用网络(SSL,...)的经验,尽管浏览了一段时间,但找不到适合我的情况的解决方案。

如果我运行以下代码:

import torchvision
from torchvision import datasets, models, transforms

model = models.densenet161(pretrained=True)

我将获得以下错误代码:

Error                                     Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
    443             try:
--> 444                 cnx.do_handshake()
    445             except OpenSSL.SSL.WantReadError:

C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\SSL.py in do_handshake(self)
   1906         result = _lib.SSL_do_handshake(self._ssl)
-> 1907         self._raise_ssl_error(self._ssl, result)
   1908 

C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\SSL.py in _raise_ssl_error(self, ssl, result)
   1638         else:
-> 1639             _raise_current_error()
   1640 

C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\_util.py in exception_from_error_queue(exception_type)
     53 
---> 54     raise exception_type(errors)
     55 

Error: [('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')]

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    599                                                   body=body, headers=headers,
--> 600                                                   chunked=chunked)
    601 

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    342         try:
--> 343             self._validate_conn(conn)
    344         except (SocketTimeout, BaseSSLError) as e:

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _validate_conn(self, conn)
    848         if not getattr(conn, 'sock', None):  # AppEngine might not have  `.sock`
--> 849             conn.connect()
    850 

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py in connect(self)
    355             server_hostname=hostname,
--> 356             ssl_context=context)
    357 

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir)
    358         if HAS_SNI and server_hostname is not None:
--> 359             return context.wrap_socket(sock, server_hostname=server_hostname)
    360 

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
    449             except OpenSSL.SSL.Error as e:
--> 450                 raise ssl.SSLError('bad handshake: %r' % e)
    451             break

SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')])",)

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    448                     retries=self.max_retries,
--> 449                     timeout=timeout
    450                 )

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    637             retries = retries.increment(method, url, error=e, _pool=self,
--> 638                                         _stacktrace=sys.exc_info()[2])
    639             retries.sleep()

C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    397         if new_retry.is_exhausted():
--> 398             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    399 

MaxRetryError: HTTPSConnectionPool(host='download.pytorch.org', port=443): Max retries exceeded with url: /models/densenet161-8d451a50.pth (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')])")))

During handling of the above exception, another exception occurred:

SSLError                                  Traceback (most recent call last)
<ipython-input-2-8056c2401db5> in <module>
      1 # load model
----> 2 model = models.densenet161(pretrained=True)
      3 print(model)

C:\ProgramData\Anaconda3\lib\site-packages\torchvision\models\densenet.py in densenet161(pretrained, **kwargs)
    114         pattern = re.compile(
    115             r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
--> 116         state_dict = model_zoo.load_url(model_urls['densenet161'])
    117         for key in list(state_dict.keys()):
    118             res = pattern.match(key)

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\model_zoo.py in load_url(url, model_dir, map_location, progress)
     64         sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
     65         hash_prefix = HASH_REGEX.search(filename).group(1)
---> 66         _download_url_to_file(url, cached_file, hash_prefix, progress=progress)
     67     return torch.load(cached_file, map_location=map_location)
     68 

C:\ProgramData\Anaconda3\lib\site-packages\torch\utils\model_zoo.py in _download_url_to_file(url, dst, hash_prefix, progress)
     70 def _download_url_to_file(url, dst, hash_prefix, progress):
     71     if requests_available:
---> 72         u = urlopen(url, stream=True)
     73         file_size = int(u.headers["Content-Length"])
     74         u = u.raw

C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py in get(url, params, **kwargs)
     73 
     74     kwargs.setdefault('allow_redirects', True)
---> 75     return request('get', url, params=params, **kwargs)
     76 
     77 

C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py in request(method, url, **kwargs)
     58     # cases, and look like a memory leak in others.
     59     with sessions.Session() as session:
---> 60         return session.request(method=method, url=url, **kwargs)
     61 
     62 

C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    531         }
    532         send_kwargs.update(settings)
--> 533         resp = self.send(prep, **send_kwargs)
    534 
    535         return resp

C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
    644 
    645         # Send the request
--> 646         r = adapter.send(request, **kwargs)
    647 
    648         # Total elapsed time of the request (approximately)

C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    512             if isinstance(e.reason, _SSLError):
    513                 # This branch is for urllib3 v1.22 and later.
--> 514                 raise SSLError(e, request=request)
    515 
    516             raise ConnectionError(e, request=request)

SSLError: HTTPSConnectionPool(host='download.pytorch.org', port=443): Max retries exceeded with url: /models/densenet161-8d451a50.pth (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')])")))

1 个答案:

答案 0 :(得分:0)

要修复ssl证书错误,请将https替换为http

import torchvision
from torchvision.models.detection.densenet import model_urls
model_urls['densenet161'] = model_urls['densenet161'].replace('https://','http://')
model = models.densenet161(pretrained=True)