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

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

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

我该怎么做呢?


当前回答

你可以使用gpg加密的netrc文件与curl像这样:

netrc_file="$HOME/netrc.gpg"
curl --netrc-file <(gpg -d $netrc_file) https://...

其他回答

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

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

简单地说,最安全的方法是使用环境变量来存储/检索凭据。因此,curl命令如下:

curl -Lk -XGET -u "${API_USER}:${API_HASH}" -b cookies.txt -c cookies.txt -- "http://api.somesite.com/test/blah?something=123"

然后调用您的restful api,并将API_USER和API_HASH的Base64编码值传递给http WWW_Authentication头。lk只是告诉curl遵循http 30x重定向并使用不安全的tls处理(即忽略ssl错误)。而double——只是bash语法中停止处理命令行标志的糖。此外,-b cookie .txt和-c cookie .txt标记处理cookie, -b发送cookie, -c本地存储cookie。

手册中有更多认证方法的示例。

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

如果是摘要认证,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'

要让密码至少不弹出在你的.bash_history:

curl -u user:$(cat .password-file) http://example-domain.tld

更安全的做法是:

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

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

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

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

注意:

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