我希望在使用内部公司链接向服务器发送请求时忽略 认证验证
。
使用 Python 的 requests
库,我会这样做:
r = requests.get(link, allow_redirects=False,verify=False)
我该如何使用urllib2库实现同样的功能?
我希望在使用内部公司链接向服务器发送请求时忽略 认证验证
。
使用 Python 的 requests
库,我会这样做:
r = requests.get(link, allow_redirects=False,verify=False)
我该如何使用urllib2库实现同样的功能?
import urllib2
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
urllib2.urlopen("https://your-test-server.local", context=ctx)
根据文档,直接调用SSLContext构造函数也应该有效。我没有尝试过。
最简单的方法:
Python 2
import urllib2, ssl
request = urllib2.Request('https://somedomain.co/')
response = urllib2.urlopen(request, context=ssl._create_unverified_context())
Python 3
from urllib.request import urlopen
import ssl
response = urlopen('https://somedomain.co', context=ssl._create_unverified_context())
from urllib.request import urlopen
,而不是 import urllib2
。
有关详细信息,请参见 https://dev59.com/5XE85IYBdhLWcg3wZyqt 中的已接受答案。 - aye2m如果您使用开启器,您可以根据Enno Gröper的出色答案实现相同的事情:
import urllib2, ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx), your_first_handler, your_second_handler[...])
opener.addheaders = [('Referer', 'http://example.org/blah.html')]
content = opener.open("https://localhost/").read()
然后像以前一样使用它。
根据 build_opener 和 HTTPSHandler,如果 ssl
模块存在,则会添加 HTTPSHandler,这里我们只是指定自己的而不是默认的。
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))
注意:以上所有测试环境都是Python 2.7.12。我在这里使用 PROTOCOL_SSLv23 ,因为文档这样说,其他协议也可能有效,但取决于您的机器和远程服务器,请查看文档了解详细信息。
add_password
中的uri
必须包含新的根URL(也可以传递URL列表)。import ssl
import urllib.parse
import urllib.request
def get_resource(uri, user, passwd=False):
"""
Get the content of the SSL page.
"""
uri = 'https://httpbin.org/basic-auth/user/passwd'
user = 'user'
passwd = 'passwd'
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, uri, user, passwd)
auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(auth_handler, urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)
return urllib.request.urlopen(uri).read()
ssl.create_default_context
仅在 Python 3.4 及以上版本中可用。 - gosrurllib2.install_opener(urllib2.build_opener(auth_handler, host_handler))
。 - Christopher Schultz