在 shell 脚本中检查 Bitbucket 登录凭据 [英] Check Bitbucket login credentials inside shell script
问题描述
我目前正在编写一个 shell/bash 脚本来自动化工作流程.这个 bash 脚本可以克隆项目并在 Bitbucket 上创建新的 repo,执行 Composer 安装/更新等等.
I'm currently writing a shell/bash script to automate a workflow. This bash script can clone projects and create new repo's on Bitbucket, do composer install/update's and more of that stuff.
我的第一个计划是通过 SSH 完成此操作,但在某些情况下我需要 HTTPS.对于所有认为通过 HTTPS 进行的操作,我需要先检查 Bitbucket 的用户凭据.由用户名和密码组成的凭据.
My first plan was to do this all over SSH, but there are some situations that I need HTTPS. For all thinks that go's over HTTPS I need to check the user credentials for Bitbucket first. The credentials consisting of a username and password.
这可能吗.如果是,怎么办?
Is this possible. If so, how?
推荐答案
正如你在评论中所建议的,curl
可以为你做 HTTP Basic Auth.对于 BitBucket,响应将是 401 Unauthorized
或 200 OK
,具体取决于用户名/密码对的有效性.您可以使用 grep
测试输出(或仅标题),但更强大的方法是使用 -w
/--write-out
选项,结合一个 HEAD
请求和 -s
静默输出:
As you suggested in comments, curl
can do HTTP Basic Auth for you. For BitBucket, the response will be 401 Unauthorized
or 200 OK
, depending on the validity of username/password pair. You could test the output (or only headers) with grep
, but a little bit more robust approach would be to use the -w
/--write-out
option, combined with a HEAD
request and -s
ilenced output:
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)
然后,为了测试状态,您可以使用一个简单的条件表达式:
Then, to test the status, you can use a simple conditional expression:
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
命令,例如:
Or, if you plan on testing multiple status codes, you can use the case
command, for example:
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
这篇关于在 shell 脚本中检查 Bitbucket 登录凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!