我试图使用python从web获取数据。我导入了urllib。请求包,但在执行时,我得到错误:

certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)

我在Mac OS High Sierra上使用Python 3.7。 我试图从CSV文件: https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv

当我将URL更改为“http”时-我能够获得数据。但是,我认为这避免了检查SSL证书。

所以我在网上找到了一个解决方案: 运行/Applications/Python\ 3.7/Install\ certificates .命令

这解决了我的问题。但是我没有SSL之类的知识。你能帮我理解一下它到底是怎么解决我的问题的吗?

如果可能的话,请给我推荐一些好的资源来了解安全与证书。我是新手。

谢谢!

注意:我确实通过链接openssl, python请求错误:“证书验证失败”

我的问题与链接中的问题不同,因为我想知道当我安装certifi包或运行install \ Certificates.command来修复错误时实际发生了什么。我对证券的理解很差。


当前回答

在我的例子中,这个错误的原因是OPENSSLDIR被设置为一个不包含实际证书的路径,可能是由于一些升级/重新安装造成的。

要验证这一点,如果这可能是你的情况,试着运行:

openssl s_client -CApath /etc/ssl/certs/ -connect some-domain.com:443

如果您删除了-CApath /etc/ssl/certs/并得到一个20的错误代码,那么这可能是原因。您也可以通过执行openssl version -a命令查看OPENSSLDIR设置为什么。

由于修改OPENSSLDIR需要重新编译,我发现最简单的解决方案就是在现有路径中创建一个符号链接:ln -s /etc/ssl/certs your-openssldir/certs

其他回答

我在OSX上遇到了同样的问题,而我的代码在Linux上完全没问题,你在你的问题中给出了答案!

在检查您指向/Applications/Python 3.7/Install certificates .command的文件后,发现该命令将默认Python安装的根证书替换为通过certifi包提供的根证书。

Certifi是根证书的集合。每个SSL证书都依赖于一个信任链:您信任一个特定的证书,因为您信任该证书的父证书,因此您信任该证书的父证书,等等。在某些情况下,没有“父”证书,这些是“根”证书。对于这些问题,除了捆绑普遍信任的根证书(通常是大型信托公司,如eg。“DigiCert”)。

例如,您可以在浏览器安全设置中看到根证书(例如Firefox->首选项->隐私和安全->视图证书->权威)。

回到最初的问题,在运行.command文件之前,在干净的安装上执行这个命令会返回一个空列表:

import os
import ssl                                        
openssl_dir, openssl_cafile = os.path.split(      
    ssl.get_default_verify_paths().openssl_cafile)
# no content in this folder
os.listdir(openssl_dir)
# non existent file
print(os.path.exists(os.path.join(openssl_dir, openssl_cafile)))

这意味着OSX上的Python安装没有默认的证书颁发机构。可能的默认值正是证书包提供的。

在此之后,您只需创建一个具有正确默认值的SSL上下文,如下所示(certificate .where()给出了证书颁发机构的位置):

import platform
# ...

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.check_hostname = True
ssl_context.load_default_certs()

if platform.system().lower() == 'darwin':
    import certifi
    ssl_context.load_verify_locations(
        cafile=os.path.relpath(certifi.where()),
        capath=None,
        cadata=None)

然后像这样从python请求一个url:

import urllib
# previous context
https_handler = urllib.request.HTTPSHandler(context=ssl_context)

opener = urllib.request.build_opener(https_handler)
ret = opener.open(url, timeout=2)

我在linux上有conda错误。我的解决办法很简单。

conda install -c conda-forge certifi

我不得不使用conda锻造,因为默认证书似乎有问题。

由于这个问题没有[macos]标签,我在ubuntu下发布了一个同样问题的解决方案:

sudo apt install ca-certificates
sudo update-ca-certificates --fresh
export SSL_CERT_DIR=/etc/ssl/certs

解决方案来自Github上的Zomatree。

Certifi提供了Mozilla精心策划的根证书集合,用于验证SSL证书的可信度,同时验证TLS主机的身份。它已经从Requests项目中提取出来。

pip install certifi

或者运行下面的程序代码:

# install_certifi.py
#
# sample script to install or update a set of default Root Certificates
# for the ssl module.  Uses the certificates provided by the certifi package:
#       https://pypi.python.org/pypi/certifi

import os
import os.path
import ssl
import stat
import subprocess
import sys

STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
             | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
             | stat.S_IROTH |                stat.S_IXOTH )


def main():
    openssl_dir, openssl_cafile = os.path.split(
        ssl.get_default_verify_paths().openssl_cafile)

    print(" -- pip install --upgrade certifi")
    subprocess.check_call([sys.executable,
        "-E", "-s", "-m", "pip", "install", "--upgrade", "certifi"])

    import certifi

    # change working directory to the default SSL directory
    os.chdir(openssl_dir)
    relpath_to_certifi_cafile = os.path.relpath(certifi.where())
    print(" -- removing any existing file or link")
    try:
        os.remove(openssl_cafile)
    except FileNotFoundError:
        pass
    print(" -- creating symlink to certifi certificate bundle")
    os.symlink(relpath_to_certifi_cafile, openssl_cafile)
    print(" -- setting permissions")
    os.chmod(openssl_cafile, STAT_0o775)
    print(" -- update complete")

if __name__ == '__main__':
    main()

Brew没有运行Mac Python3包中的Install certificates .命令。

对于那些仍然想知道如何解决这个问题的人,我通过安装“Install Certificates.command”得到了我的答案。

我是这样做的,

只需双击该文件,等待它安装,在我的情况下,你就准备好了