Created
May 18, 2015 22:53
-
-
Save iLoveTux/c0c6216dca943876da6d to your computer and use it in GitHub Desktop.
permit insecure connections with urllib2.urlopen in python 2.7.x >= 2.7.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Because migrating to python 2.7.9 requires me to update my code (or ask my clients to add cafiles to their trust store | |
# [which some people don't know how to do]), I found a way to explicitly allow insecure connections (ie. without hostname | |
# verification) using urllib2.urlopen() | |
# | |
# This gist basically involves creating an ssl.SSLContext() with some options which disable hostname verification | |
# This allows you to, for instance, add a parameter to a function which disables hostname verification. | |
import ssl | |
import urllib2 | |
import logging | |
logger = logging.getLogger(__name__) | |
logger.addHandler(logging.NullHandler) | |
def get_url(url, data=None, secure=True): | |
try: | |
context = ssl.create_default_context() | |
if not secure: | |
context.check_hostname = False | |
context.verify_mode = ssl.CERT_NONE | |
ret = urllib2.urlopen(url, data=data, context=context) | |
return ret | |
except: | |
logging.exception("Sorry, something went wrong retrieving url {}".format(url)) | |
raise | |
if __name__ == "__main__": | |
# This will NOT verify the hostname | |
get_url("https://google.com", secure=False) | |
# This one will verify the hostname | |
get_url("https://google.com") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment