Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable the ssl check in python 3.x?

Tags:

I'm using urllib.request.urlretrieve to download a file to local.

urllib.request.urlretrieve(url_string,file_name)

It throws error:

ssl.CertificateError was unhandled by user code Message: hostname 'foo.net' doesn't match either of 'a248.e.akamai.net', '.akamaihd.net', '.akamaihd-staging.net', '.akamaized.net', '.akamaized-staging.net'

If you copy the url into Chrome, it will show you a notification and you need to say something like "keep going to the url".

like image 474
Bing Gan Avatar asked Nov 18 '15 01:11

Bing Gan


People also ask

How do I stop SSL certificate warning message in Python?

This can be avoided by using urlib3. disable_warnings method. The above warning that occurred while using verify=False in the request method can be suppressed by using the urllib3. disable_warnings method.

How do I disable SSL request?

You can disable the SSL verification by simply adding verify=False as shown in the example below.

How do I enable SSL in Python?

Simple HTTPS Server using Python Also on Windows, go to https://indy.fulgan.com/SSL/openssl-1.0.2t-x64_86-win64.zip, and unzip. Afterwards on both Windows and Linux, type this command and hit enter. (This is the only command you need in Linux, but you need to do previous steps in Windows.) Copy created key.


2 Answers

Use urllib.request.urlopen with custom ssl context:

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 u, \
        open(file_name, 'wb') as f:
    f.write(u.read())

Alternatively, if you use requests library, it could be simpler:

import requests

with open(file_name, 'wb') as f:
    resp = requests.get(url_string, verify=False)
    f.write(resp.content)
like image 172
falsetru Avatar answered Sep 18 '22 16:09

falsetru


Function urllib.request.urlretrieve doesn't accept any SSL options but urllib.request.urlopen does.

However instead creating a secure SSL context with ssl.create_default_context() and making it insecure you can create an insecure context with ssl.SSLContext():

This:

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

is equivalent to:

ctx = ssl.SSLContext()

(For Python < 3.5.3 use ssl.SSLContext(ssl.PROTOCOL_TLSv1))

Which makes a nice one-liner:

import ssl
import urllib.request

with urllib.request.urlopen("https://wrong.host.badssl.com/", context=ssl.SSLContext()) as url:
    print(url.read())
like image 25
mx0 Avatar answered Sep 18 '22 16:09

mx0