Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save n1mh/bcb67cd2203a2d261ac0195f1dafacf0 to your computer and use it in GitHub Desktop.
Save n1mh/bcb67cd2203a2d261ac0195f1dafacf0 to your computer and use it in GitHub Desktop.
permit insecure connections with urllib2.urlopen in python 2.7.x >= 2.7.9
# 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