• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

Certificate validating HTTPSHandler class, VerifiedHTTPSHandler, for Python 2.7

python 水墨上仙 1284次浏览

Certificate validating HTTPSHandler class, VerifiedHTTPSHandler, for Python 2.7

from httplib import HTTPSConnection
import urllib2
import socket
import ssl
class VerifiedHTTPSConnection(HTTPSConnection):
	'''
	Modified version of the httplib.HTTPSConnection class that forces server
	certificate validation
	'''
	def __init__(self, host, port=None, key_file=None, cert_file=None,
		strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None,
		ca_file=None):
			HTTPSConnection.__init__(self, host, port, key_file,
				cert_file, strict, timeout, source_address)
			self.ca_file = ca_file
	def connect(self):
		sock = socket.create_connection(
			(self.host, self.port),
			self.timeout, self.source_address
		)
		if self._tunnel_host:
			self.sock = sock
			self._tunnel()
		if (None != self.ca_file):
			# Wrap the socket using verification with the root certs, note the hardcoded path
			self.sock = ssl.wrap_socket(
				sock,
				self.key_file,
				self.cert_file,
				cert_reqs = ssl.CERT_REQUIRED, # NEW: Require certificate validation
				ca_certs = self.ca_file # NEW: Path to trusted CA file
			)
		else:
			self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
	'''
	Modified version of the urllib2.HTTPSHandler class that uses the
	VerifiedHTTPSConnection HTTPSConnection class
	'''
	def __init__(self, debuglevel=0, key_file=None, cert_file=None, ca_file=None):
		urllib2.HTTPSHandler.__init__(self, debuglevel)
		self.key_file = key_file
		self.cert_file = cert_file
		self.ca_file = ca_file
	def https_open(self, req):
		return self.do_open(self.get_connection, req)
	def get_connection(self, host, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
		return VerifiedHTTPSConnection(host, timeout = timeout, ca_file = self.ca_file)
def main():
	# ca_file needs to be a PEM-formatted listing of certificate roots
	# See http://curl.haxx.se/ca/cacert.pem for an example
	# Or https://raw.github.com/Caligatio/nss-root-converter/master/nss-coverter-py27.py
	opener = urllib2.build_opener(VerifiedHTTPSHandler(ca_file = 'cacert.pem'))
	urllib2.install_opener(opener)
	request = urllib2.Request('https://www.google.com')
	sock = urllib2.urlopen(request)
	data = sock.read()
	print(data)
if ('__main__' == __name__):
	main()


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明Certificate validating HTTPSHandler class, VerifiedHTTPSHandler, for Python 2.7
喜欢 (0)
加载中……