我正在使用以下代码对ssl服务器执行ssl握手和证书验证。
import ssl
import socket
s = socket.socket()
print "connecting..."
#logging.debug("Connecting")
# Connect with SSL mutual authentication
# We only trust our server's CA, and it only trusts user certificates signed by it
c = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_SSLv3, ca_certs='ca.crt',
certfile='user.crt', keyfile='user.key')
c.connect((constants.server_addr, constants.port))
我能够连接到服务器并且证书被正确验证,但是,我不确定从这里做什么。我需要通过套接字执行https操作,包括将XML发布到REST API。我该怎么办?
您可以使用
wrap_socket
代码扩展httplib.HTTPConnection
,如this answer中所述。(我还是会考虑使用类似PycURL的东西,因为我已经在your previous question中回答过了。)
您可以从
urllib2.urlopen
:http://docs.python.org/library/urllib2.html#urllib2.urlopen开始它可以处理https url、抓取、发布等。您不需要直接处理低级的
socket
或ssl
对象。不过,如果您使用的是Python2.x,HTTPS连接不会对服务器端证书进行任何验证,这看起来是您所需要的(这很好)。不过,Python 3的urllib
确实做到了。如果您使用的是Python 2,那么您有几个选项。一种是对
urllib2.HTTPSHandler
进行子类划分,以便对其套接字进行适当的验证。另一个是实现您自己需要的HTTP协议位(不推荐)。您还可以正常地实例化各种urllib2
和httplib
对象,然后简单地分配您已经通过身份验证的ssl套接字来代替它们正在使用的套接字,尽管您需要非常小心,以免它们的状态变糟。不过,标准库中的源代码可读性很强,以防您需要这样做。这正是我在我的项目中所做的。这是我在项目中使用的REST客户机模块。它已经被修改以适应我的需要,但我想你可能会发现它也很有用。它需要httplib2:http://pypi.python.org/pypi/httplib2
示例用法(如果服务器证书未由指定的ca签名,则连接将失败):
相关问题 更多 >
编程相关推荐