簡體   English   中英

我如何使用python 3通過基本身份驗證下載Teamcity工件

[英]how can I use python 3 to download a Teamcity artifact with basic auth

我正在嘗試使用python 3從teamcity下載zip工件,但是我運氣不高。

在瀏覽器中,我通常會這樣做: http:// USERNAME:PWD@SERVER/httpAuth/repository/downloadAll/dood_dad/latest.last

但是,如果我使用urllib.request.urlretrieve嘗試此操作,則會收到有關無效端口的異常-因為它不知道附加在url前面的用戶名和密碼,並且會在':'之后作為端口進行解析-很公平。

所以我想我需要使用teamcitys httpAuth的東西,並使用url http://SERVERNAME/httpAuth/repository/downloadAll/dood_dad/latest.last

當我嘗試該操作時,我得到了404 Unauthorized,這是我期望的,因為我需要提供用戶名和密碼。

但是我不知道怎么做。

我添加了這個:

auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(None,
                          uri=url_to_open,
                          user='userame',
                          passwd='password')
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
local_filename, headers = urllib.request.urlretrieve(url)

但是我仍然收到HTTP錯誤401:未經授權

TIA。

您可以使用類似requests的庫,讓您將基本身份驗證作為參數,請參見此處: http : //docs.python-requests.org/en/latest/user/authentication/#basic-authentication

import requests
from requests.auth import HTTPBasicAuth
import shutil

response = requests.get('http://...', auth=HTTPBasicAuth('user', 'pass'), stream=True)

with open('filename.zip', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)

這行得通:

import urllib
from urllib.request import HTTPPasswordMgrWithDefaultRealm

pwdmgr = HTTPPasswordMgrWithDefaultRealm()
pwdmgr.add_password(None, uri=url, user='XXXX', passwd='XXXX')
auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
local_filename, headers = urllib.request.urlretrieve(url)

我不完全確定為什么更新的代碼能在較舊的代碼上起作用。

僅供參考:請求代碼也從未起作用

response = requests.get('http://...', auth=HTTPBasicAuth('user', 'pass'), stream=True)

我不斷收到未經授權的HTTP錯誤

從構建腳本獲取工件

import getpass
import subprocess

USERNAME = getpass.getuser()
PWD = getpass.getpass(prompt='PWD:', stream=None)
subprocess.run(['wget','http://'+USERNAME+':'+'PWD'+'@SERVER/httpAuth/repository/downloadAll/dood_dad/latest.lastSuccessful'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM