HTTP基本身份验证在python脚本中失败

时间:2012-08-30 17:18:10

标签: python basic-authentication urllib

我正在尝试连接到REST资源并使用Python脚本检索数据(Python 3.2.3)。当我运行脚本时,我收到错误,因为HTTP错误401:未经授权。请注意,我可以使用基本身份验证使用REST客户端访问给定的REST资源。在REST客户端中,我指定了主机名,用户和密码详细信息(不需要域)。 下面是代码和完整错误。非常感谢您的帮助。

代码:

import urllib.request

# set up authentication info
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm=None,
                       uri=r'http://hostname/',
                       user='administrator',
                       passwd='administrator')
opener =  urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
res = opener.open(r'http://hostname:9004/apollo-api/nodes')
nodes = res.read()

错误

Traceback (most recent call last):
File "C:\Python32\scripts\get-nodes.py", line 12, in <module>
    res = opener.open(r'http://tolowa.wysdm.lab.emc.com:9004/apollo-api/nodes')
File "C:\Python32\lib\urllib\request.py", line 375, in open
   response = meth(req, response)
File "C:\Python32\lib\urllib\request.py", line 487, in http_response
   'http', request, response, code, msg, hdrs)
File "C:\Python32\lib\urllib\request.py", line 413, in error
   return self._call_chain(*args)
File "C:\Python32\lib\urllib\request.py", line 347, in _call_chain
   result = func(*args)
File "C:\Python32\lib\urllib\request.py", line 495, in http_error_default
   raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Unauthorized

2 个答案:

答案 0 :(得分:4)

尝试提供正确的域名。例如,当您在浏览器中打开页面时,可以找到此信息 - 密码提示应显示名称。

答案 1 :(得分:3)

您还可以通过捕获引发的异常来阅读该领域:

import urllib.error
import urllib.request

# set up authentication info
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm=None,
                       uri=r'http://hostname/',
                       user='administrator',
                       passwd='administrator')
opener =  urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
try:
    res = opener.open(r'http://hostname:9004/apollo-api/nodes')
    nodes = res.read()
except urllib.error.HTTPError as e:
    print(e.headers['www-authenticate'])

您应该获得以下输出:

Basic realm="The realm you are after"

从上面阅读领域并在add_password方法中进行设置,这应该是好的。