📌  相关文章
📜  python ssl certificate_verify_failed (1)

📅  最后修改于: 2023-12-03 15:34:04.782000             🧑  作者: Mango

Python SSL Certificate_Verify_Failed

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.

Common Causes
  1. 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.

  2. 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.

  3. 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.

Possible Solutions
  1. 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.

  2. 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.

  1. Disable SSL Verification: If you trust the server and want to disable SSL verification, you can use the following code:
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.

  1. Configure Proxy: If there is a proxy or firewall between Python and the server, configure the proxy settings in your Python program.
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.

Conclusion

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.