我想访问一个需要用户名/密码的URL。我想用curl访问它。现在我正在做的事情是:

curl http://api.somesite.com/test/blah?something=123

我得到一个错误。我想我需要在上面的命令中指定用户名和密码。

我该怎么做呢?


当前回答

你可以使用命令,

curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext

HTTP密码将被触发。

参考: http://www.asempt.com/article/how-use-curl-http-password-protected-site

其他回答

你也可以这样发送用户名:

curl -u USERNAME http://server.example

然后Curl将要求您输入密码,并且密码将不会在屏幕上显示(或者如果您需要复制/粘贴该命令)。

要在脚本中安全地传递密码(即防止它与ps auxf或logs一起出现),您可以使用- k -标志(从stdin读取配置)和heredoc:

curl --url url -K- <<< "--user user:password"

如果你的服务器支持基本认证,你可以这样做:

printf 'header="Authorization: Basic %s"' "$(base64 --wrap=0 credentials)"|
curl --config - https://example.org

凭据是存储用户名和密码的文件,格式为username:password。

该解决方案的好处:

不需要转义特殊字符 适用于任何密码,即使它包含空格、引号、反斜杠或其他特殊字符,因此它也可以安全地用于不控制输入的脚本 在带有内置printf的shell中,登录数据不会显示在进程列表中

如果你的shell没有printf作为内置命令,你可以这样做,以避免登录数据出现在进程列表中:

{ printf 'header="Authorization: Basic '; base64 --wrap=0 credentials; printf '"'; }|
curl --config - https://example.org

使用-u标志来包含用户名,curl将提示输入密码:

curl -u username http://example.com

你也可以在命令中包含密码,但你的密码将在bash历史中可见:

curl -u username:password http://example.com

我在bash (Ubuntu 16.04 LTS)中有同样的需求,答案中提供的命令在我的情况下无法工作。我不得不使用:

curl -X POST -F 'username="$USER"' -F 'password="$PASS"' "http://api.somesite.com/test/blah?something=123"

-F参数中的双引号仅在使用变量时才需要,因此从命令行…-F 'username=myuser'…会没事的。

相关安全注意:正如Mark Ribau先生在注释中指出的那样,此命令在进程列表中显示密码($PASS变量,展开)!