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

标签 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

最佳答案

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

关于python - HTTP 基本身份验证在 python 脚本中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202156/

相关文章:

python - 在 Python 中动态覆盖 __functions__

url - 当 URL 中提供凭据时,为什么浏览器不发送 Authentication header ?

c# - MVC 和 WebAPI 网站中的身份验证

python - 如何让 Pymacs 在 Ubuntu 中使用 EPD python 工作?

Python线程运行()阻塞

python - os.nice() 的最大nice值

tomcat - 配置 ldap 身份验证后无法登录到 Tomcat 7 管理器应用程序

python - 使用 Python 从 Blob URL 下载文件

python - 使用 urllib 启用 cookie

python - urllib2.urlopen() 支持 no_proxy 环境变量吗?