【问题标题】:HTTP Basic Authentication is failing in python scriptPython 脚本中的 HTTP 基本身份验证失败
【发布时间】:2025-11-24 20:30:01
【问题描述】:

我正在尝试连接到 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

【问题讨论】:

标签: python basic-authentication urllib


【解决方案1】:

尝试给出正确的领域名称。例如,您可以在浏览器中打开页面时发现这一点 - 密码提示应显示名称。

【讨论】:

  • 这个,或者改用HTTPPasswordMgrWithDefaultRealm密码管理器。
  • 感谢 jOnes 和 @Martijn Pieters 帮助我解决了这个问题。
【解决方案2】:

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

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 方法中,应该很好。

【讨论】:

  • 感谢@Thierry Lam 帮助我解决了这个问题。
最近更新 更多