python url 2 lib HTTP Err 407

1646 ワード

会社のネットワーク環境はプロキシを通じてインターネットを利用しています。python url 2 lib普通のプロキシで検証できません。
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 Errror 407:Proxy Authentication Required(Forefront TMG requires authorization to fulfill the request.
調べてみると、会社のネットワークエージェントがNTLMを使って検証していることが分かりました。python ntmlパッケージをインストールして検証を完了する必要があります。
簡単でストレートです easymuinstall 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())
 一発限りの成功