Python 3 urllib ignore SSL certificate validation

I have a server setup for testing with a self-signed certificate and you want to check it.

How to ignore SSL validation in Python 3 urlopen ?

All the information I have found regarding this relates to urllib2 or Python 2. In general.

urllib in python 3 changed from urllib2 :

Python 2, urllib2 : urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

https://docs.python.org/2/library/urllib2.html#urllib2.urlopen

Python 3 : urllib.request.urlopen(url[, data][, timeout]) https://docs.python.org/3.0/library/urllib.request.html?highlight=urllib#urllib.request.urlopen

So, I know that this can be done in Python 2 as follows. However, in Python 3 urlopen no context parameter.

 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) 

And yes, I know this is a bad idea. This is for testing on a private server only.

I could not find how this should be done in the Python 3 documentation or in any other question. Even those that explicitly mention Python 3 still had a solution for urllib2 / Python 2.

+15
source share
2 answers

Python 3.0 to 3.3 does not have a context parameter; it was added in Python 3.4. This way you can upgrade your version of Python to 3.5 to use context.

+5
source

The accepted answer just gave advice to use python 3. 5+ instead of a direct answer. This is confusing.

For those seeking a direct answer, here it is:

 import ssl import urllib.request ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with urllib.request.urlopen(url_string, context=ctx) as f: f.read(300) 

Alternatively, if you use the requests library, it has a much better API:

 import requests with open(file_name, 'wb') as f: resp = requests.get(url_string, verify=False) f.write(resp.content) 

The answer is copied from this post (thanks @ falsetru ): How to disable ssl checking in python 3.x?

These two questions should be combined.

0
source

Source: https://habr.com/ru/post/1247042/


All Articles