python - HTTP 错误 401 : Unauthorized using urllib. request.urlopen

标签 python teamcity

我在 python 中使用 urllib.request 来尝试从 Teamcity 下载一些构建信息。此请求过去无需用户名和密码即可工作,但最近的安全更改意味着我必须使用用户名和密码。所以我改变了尝试以下两种解决方案中的每一种:

尝试 1)

url = 'http://<domain>/httpAuth/app/rest/buildTypes/<buildlabel>/builds/running:false?count=1&start=0'

# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
top_level_url = "http://<domain>/httpAuth/app/rest/buildTypes/id:<buildlabel>/builds/running:false?count=1&start=0"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
opener.open(url)

尝试 2

url = 'http://<username>:<password>@<domain>/httpAuth/app/rest/buildTypes/id:buildlabel/builds/running:false?count=1&start=0'
rest_api = urllib.request.urlopen(url)

这两个都返回“HTTP 错误 401:未经授权”。但是,如果我要打印“url”并将此输出复制到浏览器中,则该链接可以正常工作。但是当通过 python 使用时,我得到了上面的错误。

我在另一个 Perl 脚本中使用了非常相似的东西,这也非常有效。

* 解决如下 *

最佳答案

解决了这个问题。

credentials(url, username, password)
rest_api = urllib2.urlopen(url)
latest_build_info = rest_api.read()
latest_build_info = latest_build_info.decode("UTF-8")
# Then parse this xml for the information I want. 

def credentials(self, url, username, password):
    p = urllib2.HTTPPasswordMgrWithDefaultRealm()
    p.add_password(None, url, username, password)
    handler = urllib2.HTTPBasicAuthHandler(p)
    opener = urllib2.build_opener(handler)
    urllib2.install_opener(opener)

作为旁注,我想下载一个文件..

credentials(url, username, password)
urllib2.urlretrieve(url, downloaded_file)

网址在哪里:

http://<teamcityServer>/repository/download/<build Label>/<BuildID>:id/Filename.zip

关于python - HTTP 错误 401 : Unauthorized using urllib. request.urlopen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221579/

相关文章:

git - 使用 GitVersion 作为 TeamCity 中的构建步骤的私有(private)存储库连接错误

python - 与 tif 一起保存图像元数据的最佳方法是什么?

Python 打印在不同服务器上的工作方式不同

python - 如何从 Python 中的字符串中提取数字?

python - 使用 python 请求从 oanda V20 Rest api 流式定价

python - NumPy 的错误? ( python 3)

msbuild - teamcity MSBuild 错误, "A signing key is required in order to package this project"

.net - TeamCity和MSBuild集成

svn - 使TeamCity将Subversion内部版本号集成到程序集版本中

msbuild - 来自 TeamCity 的 MSBuild 的/P MSDeploy 参数的完整列表