Python requests equivalent of '--proxy-header' in curl with SSL certification

我怕爱的太早我们不能终老 提交于 2020-01-05 05:47:06

问题


Reference: How does one specify the equivalent of `--proxy-headers` curl argument into requests?

I am a newbie vis-a-vis Python.

I have a requirement, where a request to a destination(webpage) must go through a proxy server.

  • I need to pass headers to the "Proxy server" (same as --proxy-header of curl)
  • Need to add an SSL certificate (a '.cer' file) to read the passed headers to the proxy server(a 'Man In the Middle' scenario) on CONNECT.

The curl equivalent of my requirement is as follows:

curl -k --verbose --cacert /proxy/cert/folder/proxy-certificate.cer --proxy-header "header1: value1" --proxy 'http://localhost:8080/' 'https://destination.com'

I did come across a similar example How does one specify the equivalent of `--proxy-headers` curl argument into requests?. But I am unsure how to incorporate this with an SSL certificate.

My Code:


proxyheaders = { 'http://localhost:9090/': { 'header1': 'value1' } }

class ProxyHeaderAwareHTTPAdapter(requests.adapters.HTTPAdapter):
    def proxy_headers(self, proxy):
        if proxy in proxyheaders:
            return proxyheaders[proxy]
        else:
            return None

s = requests.Session()
s.mount('http://', ProxyHeaderAwareHTTPAdapter())
s.mount('https://', ProxyHeaderAwareHTTPAdapter())
URL = "https://stackoverflow.com/"
cert_file_path = "/Path/to/certificate/proxy-certificate.cer"
try:
    s.get(URL, verify=cert_file_path)
except Exception as e:
    print(e)

I get the following error:

HTTPSConnectionPool(host='stackoverflow.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)')))

回答1:


THIS IS NOT A SOLUTION:

When i usually encounter certificate/verification errors, i just force it to not verify the certificate using the code below:

conda config --set ssl_verify false

Note that this is not usually recommended and i usually do it temporarily until i finish either running spicific script or downloading a library or so. If you want to try this and if it works for you, remember to turn it back on once done using the code below:

conda config --set ssl_verify true


来源:https://stackoverflow.com/questions/59386500/python-requests-equivalent-of-proxy-header-in-curl-with-ssl-certification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!