简体   繁体   English

HTTP错误401:未经授权使用urllib.request.urlopen

[英]HTTP Error 401: Unauthorized using urllib.request.urlopen

I'm using urllib.request in python to try and download some build information from Teamcity. 我在python中使用urllib.request尝试从Teamcity下载一些构建信息。 This request used to work without username and password, however a recent security change means I must use a username and password. 该请求曾经在没有用户名和密码的情况下工作,但是最近的安全更改意味着我必须使用用户名和密码。 So I have changed tried each of the two solutions below: 因此,我更改了以下两种解决方案的尝试:

Attempt 1) 尝试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)

Attempt 2 尝试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)

Both of these return "HTTP Error 401: Unauthorized". 这两个都返回“ HTTP错误401:未经授权”。 However if I was to print 'url' and copy this output into a browser the link works perfectly. 但是,如果我要打印'url'并将此输出复制到浏览器中,则该链接可以正常工作。 But when used through python I get the above error. 但是当通过python使用时,出现上述错误。

I use something very similar in another Perl script and this works perfectly also. 我在另一个Perl脚本中使用了非常相似的东西,这也很完美。

* SOLVED BELOW * *解决以下*

Solved this using. 解决了这个使用。

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)

As a side note, I then want to download a file.. 作为旁注,然后我要下载文件。

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

Where Url is: 网址在哪里:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM