HTTPS 连接 Python

发布于 2024-08-19 04:32:09 字数 1882 浏览 14 评论 0原文

我正在尝试验证该目标是否公开了 https Web 服务。我有通过 HTTP 连接的代码,但我不确定如何通过 HTTPS 连接。我读到您使用 SSL,但我也读到它不支持证书错误。我得到的代码来自 python 文档:

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason

有谁知道如何连接到 HTTPS?

我已经尝试过 HTTPSConenction,但它响应一个错误代码,声称 httplib 没有属性 HTTPSConnection。我也没有可用的 socket.ssl 。

我已经安装了 Python 2.6.4,但我认为它没有编译 SSL 支持。有没有办法将此支持集成到较新的 python 中,而无需再次安装。

我已经安装了 OpenSSL 和 pyOpenSsl,并且尝试了以下答案之一的代码:

import urllib2
from OpenSSL import SSL
try: 
    response = urllib2.urlopen('https://example.com')  
    print 'response headers: "%s"' % response.info() 
except IOError, e: 
    if hasattr(e, 'code'): # HTTPError 
        print 'http error code: ', e.code 
    elif hasattr(e, 'reason'): # URLError 
        print "can't connect, reason: ", e.reason 
    else: 
        raise

我收到错误:

    Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 203, in open
    return self.open_unknown(fullurl, data)
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 215, in open_unknown
    raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

有谁知道如何让它工作吗?

-- UPDATE

我已经发现问题所在了,我使用的Python版本不支持SSL。我目前在以下位置找到了此解决方案: http://www.webtop.com .au/compiling-python-with-ssl-support

在这个解决方案之后,代码现在可以工作了,这非常好。当我导入 ssl 和 HTTPSConnection 时,我知道不会出现错误。

感谢大家的帮助。

I am trying to verify the that target exposes a https web service. I have code to connect via HTTP but I am not sure how to connect via HTTPS. I have read you use SSL but I have also read that it did not support certificate errors. The code I have got is from the python docs:

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print r1.status, r1.reason

Does anyone know how to connect to HTTPS?

I already tried the HTTPSConenction but it responds with an error code claiming httplib does not have attribute HTTPSConnection. I also don't have socket.ssl available.

I have installed Python 2.6.4 and I don't think it has SSL support compiled into it. Is there a way to integrate this suppot into the newer python without having to install it again.

I have installed OpenSSL and pyOpenSsl and I have tried the below code from one of the answers:

import urllib2
from OpenSSL import SSL
try: 
    response = urllib2.urlopen('https://example.com')  
    print 'response headers: "%s"' % response.info() 
except IOError, e: 
    if hasattr(e, 'code'): # HTTPError 
        print 'http error code: ', e.code 
    elif hasattr(e, 'reason'): # URLError 
        print "can't connect, reason: ", e.reason 
    else: 
        raise

I have got an error:

    Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 203, in open
    return self.open_unknown(fullurl, data)
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/urllib.py", line 215, in open_unknown
    raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

Does anyone know how to get this working?

-- UPDATE

I have found out what the problem was, the Python version I was using did not have support for SSL. I have found this solution currently at: http://www.webtop.com.au/compiling-python-with-ssl-support.

The code will now work after this solution which is very good. When I import ssl and HTTPSConnection I know don't get an error.

Thanks for the help all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

北陌 2024-08-26 04:32:09

Python 2.x:docs.python.org/2/library/httplib.html

注意:仅当套接字模块使用 SSL 支持进行编译时,HTTPS 支持才可用。

Python 3.x:docs.python.org/3/library/http.client。 html

注意,仅当 Python 编译时支持 SSL(通过 ssl 模块)时,HTTPS 支持才可用。

#!/usr/bin/env python

import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# => 
# 200 OK
# <!DOCTYPE html ....

要验证 SSL 是否已启用,请尝试:

>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>

Python 2.x: docs.python.org/2/library/httplib.html:

Note: HTTPS support is only available if the socket module was compiled with SSL support.

Python 3.x: docs.python.org/3/library/http.client.html:

Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).

#!/usr/bin/env python

import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# => 
# 200 OK
# <!DOCTYPE html ....

To verify if SSL is enabled, try:

>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>
带上头具痛哭 2024-08-26 04:32:09

要检查 Python 2.6+ 中的 ssl 支持

try:
    import ssl
except ImportError:
    print "error: no ssl support"

通过 https

import urllib2

try:
    response = urllib2.urlopen('https://example.com') 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise

To check for ssl support in Python 2.6+:

try:
    import ssl
except ImportError:
    print "error: no ssl support"

To connect via https:

import urllib2

try:
    response = urllib2.urlopen('https://example.com') 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise
焚却相思 2024-08-26 04:32:09
import requests
r = requests.get("https://stackoverflow.com") 
data = r.content  # Content of response

print r.status_code  # Status code of response
print data
import requests
r = requests.get("https://stackoverflow.com") 
data = r.content  # Content of response

print r.status_code  # Status code of response
print data
余生一个溪 2024-08-26 04:32:09

如果使用httplib.HTTPSConnection:

请看一下:

版本 2.7.9 中已更改

此类现在执行所有必要的证书和主机名
默认检查。恢复到之前未经验证的行为
ssl._create_unverified_context() 可以传递给上下文
范围。您可以使用:

if hasattr(ssl, '_create_unverified_context'):
  ssl._create_default_https_context = ssl._create_unverified_context

If using httplib.HTTPSConnection:

Please take a look at:

Changed in version 2.7.9:

This class now performs all the necessary certificate and hostname
checks by default. To revert to the previous, unverified, behavior
ssl._create_unverified_context() can be passed to the context
parameter. You can use:

if hasattr(ssl, '_create_unverified_context'):
  ssl._create_default_https_context = ssl._create_unverified_context
无人接听 2024-08-26 04:32:09

你为什么没有尝试过httplib.HTTPSConnection?它不执行 SSL 验证,但通过 https 连接不需要这样做。
您的代码在 https 连接下运行良好:

>>> import httplib
>>> conn = httplib.HTTPSConnection("mail.google.com")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK

Why haven't you tried httplib.HTTPSConnection? It doesn't do SSL validation but this isn't required to connect over https.
Your code works fine with https connection:

>>> import httplib
>>> conn = httplib.HTTPSConnection("mail.google.com")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
灰色世界里的红玫瑰 2024-08-26 04:32:09

假设 socket 模块启用了 SSL 支持。

connection1 = httplib.HTTPSConnection('www.somesecuresite.com')

Assuming SSL support is enabled for the socket module.

connection1 = httplib.HTTPSConnection('www.somesecuresite.com')
苍景流年 2024-08-26 04:32:09

我有一些代码因 HTTPConnection (MOVED_PERMANENTLY error) 而失败,但是当我切换到 HTTPS 时,它就再次完美运行,无需进行其他更改。这是一个非常简单的修复!

I had some code that was failing with an HTTPConnection (MOVED_PERMANENTLY error), but as soon as I switched to HTTPS it worked perfectly again with no other changes needed. That's a very simple fix!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文