公司的网络环境是通过代理上网,用python url2lib普通的代理验证不能通过,示例代码:
url = 'www.python.org' username = 'user' password = 'pass' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() # None, with the "WithDefaultRealm" password manager means # that the user/pass will be used for any realm (where # there isn't a more specific match). password_mgr.add_password(None, url, username, password) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) print urllib2.urlopen("http://www.python.org")
仍然会报以下错误:
HTTP Error 407: Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request.
查了一下,发现跟公司网络代理使用NTLM验证有关,需要安装python ntml包来完成验证。
简单直接用 easy_install python-ntlm
安装好后下面是官方简单的连接代码:
import urllib2 from ntlm import HTTPNtlmAuthHandler user = 'domain\user' password = "pass" url = "http://www.python.org" passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, url, user, password) # create the NTLM authentication handler auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) # create and install the opener opener = urllib2.build_opener(auth_NTLM) urllib2.install_opener(opener) # retrieve the result response = urllib2.urlopen(url) print(response.read())
一次性成功。