General

How to fix python SSL CERTIFICATE_VERIFY_FAILED

Here I explain how to fix Python SSL errors when trying to access DirectAdmin API using the https protocol in Python (e.g. by using the urllib, urllib2. httplib or requests). This error looks like:

    raise ApiError("HTTP Error: %s" % e.reason)
directadmin.api.ApiError: HTTP Error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)

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