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

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

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

我该怎么做呢?


当前回答

在某些API中它可能不起作用(比如rabbitmq)。

还有其他选择:

curl http://username:password@example.com

curl http://admin:123456@example.com

上面的格式也可以在浏览器中使用。

其他回答

更安全的做法是:

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

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

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

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

注意:

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

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

curl -u USERNAME http://server.example

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

curl -X GET -u username:password  {{ http://www.example.com/filename.txt }} -O

很简单,做以下几点:

curl -X GET/POST/PUT <URL> -u username: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