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

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

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

我该怎么做呢?


当前回答

其他回答建议netrc指定用户名和密码,根据我所读到的,我同意。下面是一些语法细节:

https://ec.haxx.se/usingcurl-netrc.html

和其他回答一样,我想在这个问题上强调,要注意安全。

虽然我不是专家,但我发现这些链接很有见地:

https://ec.haxx.se/cmdline-passwords.html

总结:

使用加密版本的协议(HTTPS vs HTTP) (FTPS vs FTP)可以帮助避免网络泄漏。

使用netrc可以帮助避免命令行泄漏。

更进一步,似乎还可以使用gpg加密netrc文件

https://brandur.org/fragments/gpg-curl

这样,您的凭据就不会“静止”(存储为纯文本)。

其他回答

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

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

如果你在一个有Gnome密匙环应用程序的系统上,避免直接暴露密码的解决方案是使用gkeyring.py从密匙环中提取密码:

server=server.example.com
file=path/to/my/file
user=my_user_name
pass=$(gkeyring.py -k login -tnetwork -p user=$user,server=$server -1)

curl -u $user:$pass ftps://$server/$file -O

我在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变量,展开)!

您应该确定身份验证类型。

如果是摘要认证,http头为:

GET /xxxxxxxxxxx HTTP/1.1
Host: 192.168.3.142
User-Agent: Go-http-client/1.1
Authorization: Digest username="admin", realm="admin@51200304-49-test", nonce="5.1722929000077545", uri="/xxxxxxxxxxx", response="52d30eba90820f2c4fa4d3292a4a7bbc", cnonce="f11900fe0906e3899e0cc431146512bb", qop=auth, nc=00000001
Accept-Encoding: gzip

你可以使用——digest选项:

    curl  --digest -u 'username:password' 'http://xxxxxxxxxxx'

更安全的做法是:

curl --netrc-file my-password-file http://example.com

...由于在命令行上传递普通的用户/密码字符串,这是一个坏主意。

密码文件的格式为(按照man curl):

machine <example.com> login <username> password <password>

注意:

机器名不能包含https://或类似!只有主机名。 “machine”、“login”和“password”只是关键词;真正的信息是那些关键字之后的东西。