2017-08-07 32 views
1

我目前正在編寫一個shell/bash腳本來自動執行工作流程。這個bash腳本可以克隆項目並在Bitbucket上創建新的回購,做作曲者安裝/更新和更多的東西。檢查shell腳本內的Bitbucket登錄憑證

我的第一個計劃是通過SSH完成這項工作,但有些情況下我需要HTTPS。對於所有人認爲,經過HTTPS我需要首先檢查Bitbucket的用戶憑據。憑據由用戶名和密碼組成。

這是可能的。如果是這樣,怎麼樣?

+1

你不能只是用-u捲曲然後檢查返回的錯誤代碼 –

+0

你的意思是類似'curl -X GET -v -u「username:password」-H「Content-Type: application/json「\ https:// api.bitbucket.org/2.0/repositories/$ B_REPO_OWNER'。我怎麼能把它放在像'if [check] ...'這樣的檢查中。 – CodeWhisperer

+0

我想你會需要grep對數據,你希望返回一個成功的登錄,然後在你的if語句中使用返回碼($?)。 –

回答

2

正如您在評論中建議的,curl可以爲您執行HTTP基本身份驗證。對於BitBucket,響應將爲401 Unauthorized200 OK,具體取決於用戶名/密碼對的有效性。你可以用grep測試輸出(或僅標題),但多一點點強大的方法是使用-w/--write-out選項,具有HEAD請求-s ilenced輸出組合:

http_status=$(curl -X HEAD -s -w '%{http_code}' \ 
       -u "username:password" -H "Content-Type: application/json" \ 
       https://api.bitbucket.org/2.0/repositories/$repo_owner) 

然後,測試狀態,你可以使用一個簡單的條件表達式:

if [[ $http_status == 200 ]]; then 
    echo "Credentials valid" 
else 
    if [[ $http_status == 401 ]]; then 
     echo "Credentials INVALID" 
    else 
     echo "Unexpected HTTP status code: $http_status" 
    fi 
fi 

或者,如果你打算在測試多個狀態代碼,你可以使用case命令,例如:

case $http_status in 
    200) echo "Credentials valid";; 
    301|302) echo "API endpoint changed";; 
    401) echo "Credentials INVALID";; 
    5*) echo "BitBucket Internal server error";; 
    *) echo "Unexpected HTTP status code: $http_status";; 
esac 
+1

這非常有用! – CodeWhisperer