📅  最后修改于: 2023-12-03 15:34:04.782000             🧑  作者: Mango
If you are seeing the error "certificate_verify_failed" while running a Python program that requires SSL/TLS communication, it might indicate that there is an issue with the SSL certificate.
This error occurs when Python tries to verify the SSL certificate of the server and fails to establish a secure connection. By default, Python uses a system-wide SSL certificate store to verify the server's certificate. If the certificate is not trusted or is not valid, Python will raise the "certificate_verify_failed" error.
Expired or Invalid SSL Certificate: If the SSL certificate of the server is expired or invalid, Python will not be able to establish a secure connection.
Self-Signed SSL Certificate: If the server is using a self-signed SSL certificate, Python will not be able to verify the certificate as it is not signed by a trusted certificate authority.
Proxy or Firewall: If there is a proxy or firewall between Python and the server, it might block the SSL handshake and cause the "certificate_verify_failed" error.
Update SSL Certificate: If the SSL certificate of the server is expired or invalid, update it with a valid one. Contact the server administrator to resolve the issue.
Trust Self-Signed SSL Certificates: If the server is using a self-signed SSL certificate, you can add it to the trusted SSL certificate store of Python. Use the following code to add the certificate:
import ssl
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations('/path/to/certificate.pem')
Replace '/path/to/certificate.pem' with the path to the certificate file on your system.
import ssl
import urllib.request
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
response = urllib.request.urlopen('https://example.com', context=ssl_context)
This code disables SSL verification for the current session and ignores the SSL errors.
import os
os.environ['http_proxy'] = 'http://proxy.server:port'
os.environ['https_proxy'] = 'https://proxy.server:port'
Replace 'proxy.server' and 'port' with the actual proxy server address and port number.
The "certificate_verify_failed" error in Python indicates an issue with the SSL certificate of the server. You can follow the above solutions to resolve the issue and establish a secure SSL/TLS connection.