简体   繁体   English

通过curl登录在bash脚本中失败,相同的curl在命令行中成功

[英]Login via curl fails inside bash script, same curl succeeds on command line

I'm running this login via curl in my bash script. 我正在bash脚本中通过curl运行此登录名。 I want to make sure I can login before executing the rest of the script, where I actually log in and store the cookie in a cookie jar and then execute another curl in the API thousands of times. 我想确保在执行脚本的其余部分之前可以登录,然后在该脚本中实际登录并将cookie存储在cookie罐中,然后在API中执行数千次curl。 I don't want to run all that if I've failed to login. 如果我无法登录,我不想运行所有操作。

Problem is, the basic login returns 401 when it runs inside the script. 问题是,基本登录在脚本中运行时会返回401。 But when I run the exact same curl command on the command line, it returns 200! 但是,当我在命令行上运行完全相同的curl命令时,它将返回200!

basic_login_curl="curl -w %{http_code} -s -o /dev/null -X POST -d \"username=$username&password=$password\" $endpoint/login"
echo $basic_login_curl
outcome=`$basic_login_curl`
echo $outcome
if [ "$outcome" == "401" ]; then
    echo "Failed login. Please try again."; exit 1;
fi

This outputs: 输出:

curl -w %{http_code} -s -o /dev/null -X POST -d "username=bdunn&password=xxxxxx" http://stage.mysite.it:9301/login
401
Failed login. Please try again.

Copied the output and ran it on the cmd line: 复制输出并在cmd行上运行:

$ curl -w %{http_code} -s -o /dev/null -X POST -d "username=bdunn&password=xxxxxx" http://stage.mysite.it:9301/login
200$

Any ideas? 有任何想法吗? LMK if there's more from the code you need to see. LMK,如果您需要查看更多代码。

ETA: Please note: The issue's not that it doesn't match 401, it's that running the same curl login command inside the script fails to authenticate, whereas it succeeds when I run it on the actual CL. ETA:请注意:问题不在于它与401不匹配,是因为在脚本中运行相同的curl登录命令无法通过身份验证,而在实际的CL上运行时,它会成功。

Most of the issues reside in how you are quoting/not quoting variables and the subshell execution. 大多数问题都在于如何引用/不引用变量以及子shell执行。 Setting up your command like the following is what I would recommend: 我建议您像下面这样设置您的命令:

basic_login_curl=$(curl -w "%{http_code}" -s -o /dev/null -X POST -d "username=$username&password=$password" "$endpoint/login")

The rest basically involves quoting everything properly: 其余的基本上涉及正确引用所有内容:

basic_login_curl=$(curl -w "%{http_code}" -s -o /dev/null -X POST -d "username=$username&password=$password" "$endpoint/login")
# echo "$basic_login_curl" # not needed since what follows repeats it.
outcome="$basic_login_curl"
echo "$outcome"
if [ "$outcome" = "401" ]; then
    echo "Failed login. Please try again."; exit 1;
fi

Running the script through shellcheck.net can be helpful in resolving issues like this as well. 通过shellcheck.net运行脚本也有助于解决此类问题。

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

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