2016-10-24 19 views
1

私はTeamcityからいくつかのビルド情報を試してみるために、pythonでurllib.requestを使用しています。このリクエストはユーザー名とパスワードなしで動作することが前提でしたが、最近のセキュリティ変更により、ユーザー名とパスワードを使用する必要があります。HTTPエラー401:urllib.request.urlopenを使用して無許可

試み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:許可されていない" の両方:だから私は、下の2つの溶液のそれぞれを試してみました変更されました。しかし、私が 'url'を印刷してこの出力をブラウザにコピーすると、リンクは完全に機能します。しかし、私は上記のエラーを取得するPythonを使用しています。

別のPerlスクリプトで非常によく似た何かを使用していますが、これも完全に動作します。

* BELOW解決しよう*

+0

サーバーは、他の要素を確認すること - HTTPヘッダ、クッキーのように、 DevToolsをChrome/Firefoxで使用して、どのブラウザがサーバーに送信するかを確認できます。 HTTPヘッダー。 – furas

答えて

1

使用してこれを解決しました。

側の注意点として
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) 

URLは

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

urllib2にはurlretrieveメソッドがありませんか?それは明白なオール 'ウルリブだろう – Yusufk

関連する問題