修复用py2exe(或PyInstaller)编译的exe中的SSL证书错误

Jam*_*ull 10 python ssl py2exe pyinstaller python-requests

我刚刚完成了一个Python程序的测试,该程序涉及登录到站点并需要设置CSRF cookie.我已经尝试将其打包为exe使用py2exe并出现套接字错误.我尝试时遇到同样的问题PyInstaller.谷歌搜索Errno我发现其他一些人有同样的问题,所以我知道问题是与SLL证书的位置有关.

这是我的site_agent课程,包括日志记录调用.

    class site_agent:
        self.get_params()
        URL = root_url + '/accounts/login/'        
        # Retrieve the CSRF token first
        self.agent = requests.session()
        self.agent.get(URL)  # retrieves the cookie # This line throws the error
        self.csrftoken = self.agent.cookies['csrftoken']    
        # Set up login data including the CSRF cookie
        login_data = {'username': self.username,
                      'password': self.password,
                      'csrfmiddlewaretoken' : self.csrftoken}
        # Log in
        logging.info('Logging in')
        response = self.agent.post(URL, data=login_data, headers=hdr)
Run Code Online (Sandbox Code Playgroud)

该错误出现在该self.agent.get(URL)行,Traceback显示:

Traceback (most recent call last):
  File "<string>", line 223, in <module>
  File "<string>", line 198, in main
  File "<string>", line 49, in __init__
  File "C:\pyinstaller-2.0\pyinstaller-2.0\autoresponder\b
uild\pyi.win32\autoresponder\out00-PYZ.pyz\requests.sessions", line 350, in get
  File "C:\pyinstaller-2.0\pyinstaller-2.0\autoresponder\b
uild\pyi.win32\autoresponder\out00-PYZ.pyz\requests.sessions", line 338, in requ
est
  File "C:\pyinstaller-2.0\pyinstaller-2.0\autoresponder\b
uild\pyi.win32\autoresponder\out00-PYZ.pyz\requests.sessions", line 441, in send

  File "C:\pyinstaller-2.0\pyinstaller-2.0\autoresponder\b
uild\pyi.win32\autoresponder\out00-PYZ.pyz\requests.adapters", line 331, in send

requests.exceptions.SSLError: [Errno 185090050] _ssl.c:336: error:0B084002:x509
certificate routines:X509_load_cert_crl_file:system lib
Run Code Online (Sandbox Code Playgroud)

这是否意味着问题在于requests.adapters

如果是这样,我可以在已安装的Python包中编辑它以在其他地方查找cacert.pem,用py2exe或重建我的exe PyInstaller,然后在我安装的Python版本中将其更改回来吗?

编辑

我现在在编译PyInstaller和设置verify=False所有requests.get()requests.post()调用后运行该程序.但SSL是有原因的,我真的希望能够在让任何人使用该工具之前修复此错误.

frm*_*ryr 5

如果使用 pyinstaller...为请求库创建一个hook-requests.py文件,其中包含PyInstaller\hooks\

from hookutils import collect_data_files

# Get the cacert.pem
datas = collect_data_files('requests') 
Run Code Online (Sandbox Code Playgroud)


HVS*_*HVS 5

如果您使用“请求”模块,这可以轻松解决。

1)将以下代码放在使用“请求”模块的主python文件中

os.environ['REQUESTS_CA_BUNDLE'] = "certifi/cacert.pem"
Run Code Online (Sandbox Code Playgroud)

2) 在 exe 所在的可分发文件夹中,创建一个名为“certifi”的文件夹,并将“cacert.pem”文件放入其中。

3)您可以通过以下方式找到“cacert.pem”文件

pip install certifi

import certifi
certifi.where()
Run Code Online (Sandbox Code Playgroud)

太棒了.. 现在您的发行版包括验证 ssl 调用所需的证书。