Python无法使用ntlm进行身份验证

时间:2013-09-02 05:25:17

标签: python http authentication urllib2 ntlm

我正在尝试在我的Intranet上解析一个站点,并且在进行身份验证时,我得到一个错误,说明需要身份验证,我已经完成了。为什么我仍然会收到401错误?

提前致谢!

  

文件“C:\ Python27 \ lib \ urllib2.py”,第531行,在http_error_default中   提出HTTPError(req.get_full_url(),code,msg,hdrs,fp)   urllib2.HTTPError:HTTP错误401:需要授权

import urllib2
from ntlm import HTTPNtlmAuthHandler

user = r'domain\myuser'
password = 'mypasswd'
url = 'http://myinternal.homepage'

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)

1 个答案:

答案 0 :(得分:1)

尽量不要将'r'放在'domain \ myuser'前面。我没有'r'使用过它,它对我有用。有一件事帮助了我 - (我猜你可能已经做过......以防万一)但检查网址返回给你的标题。我使用Mechanize http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/执行了此操作,并根据返回的标头计算出我应该使用NTLM auth(如此处所示)。我也有类似的问题How to 'convert' variable of type instance such that the variable can be used to authenticate when making system calls