How to fix Python SSL CERTIFICATE_VERIFY_FAILED

More Less
1 min readMar 26, 2019

On a router with merlin firmware, I installed entware and python,

after I ran speedtest python script.

It shows error:

python2.7# speedtest
Retrieving speedtest.net configuration...
Cannot retrieve speedtest configuration
ERROR: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:726)>

how to fix Python SSL errors when downloading web pages using the https protocol in Python (e.g. by using the urllib, urllib2, httplib or requests. This error looks like (possibly with a line number different from 590):

self._sslobj.do_handshake()   SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

Server certificate verification by default has been introduced to Python recently (in 2.7.9). This protects against man-in-the-middle attacks, and it makes the client sure that the server is indeed who it claims to be.

As a quick (and insecure) fix, you can turn certificate verification off, by:

  1. Set PYTHONHTTPSVERIFY environment variable to 0. For example, run
export PYTHONHTTPSVERIFY=0
python your_script

or

PYTHONHTTPSVERIFY=0 python your_script

2. Alternatively, you can add this to your code before doing the https request

import os, ssl
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context

--

--