python ignore certificate validation urllib2

Sangamesh Hs picture Sangamesh Hs · Oct 9, 2013 · Viewed 128.5k times · Source

I want to ignore the certification validation during my request to the server with an internal corporate link.

With python requests library I would do this:

r = requests.get(link, allow_redirects=False,verify=False)

How do I do the same with urllib2 library?

Answer

Enno Gröper picture Enno Gröper · Jan 20, 2015

In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).

My evil workaround (don't do this in production!):

import urllib2
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

urllib2.urlopen("https://your-test-server.local", context=ctx)

According to docs calling SSLContext constructor directly should work, too. I haven't tried that.