kum*_*ori 5 cookies bash groovy curl
我想访问包含数据的 json 页面。比如说,它在http://example.com/home/apples.json
它的保护之下,所以显示了一个登录页面。如果我要手动访问它,我首先去http://example.com/那里我得到一个登录菜单,登录后说用户“test”和密码“test”访问http://example.com/home/apples.json again将向我显示json数据。
如果我做一个
curl -u test:test http://example.com/home/apples.json -v
Run Code Online (Sandbox Code Playgroud)
我最终在登录页面。(尽管经过身份验证。)
如果我访问http://example.com/并手动登录,我会在登录后得到一个 cookie。假设这个 cookie 被称为 ltoken 并获得值“dj8f”。它只会在成功登录后显示。当我通过浏览器查找并复制 cookie 数据并将其附加到 curl 命令时:
curl -b "ltoken="dj8f" http://example.com/home/apples.json -v
Run Code Online (Sandbox Code Playgroud)
它会起作用。
如何在不手动执行的情况下从登录后获取 cookie 数据?是否可以通过 bash shell 脚本编写方式?如果是如何?或者,如何在 groovy 脚本中完成?
sau*_*ger 12
您必须首先使用 curl 执行正确的登录。为此,请导航到登录页面并查看源代码。登录表单应如下所示。
<form action="http://example.com/login/target" method="POST">
<input type="text" name="username" />
<input type="password" name="passphrase" />
<input type="submit" value="Log in" />
</form>
Run Code Online (Sandbox Code Playgroud)
(我假设没有隐藏的输入字段。隐藏的输入字段通常用于防止请求伪造,这基本上是我们要做的。)
从这个片段中,您必须提取登录请求的目标(在本例中http://example.com/login/target)HTML 输入字段的名称(此处username和passphrase)。要执行登录过程,您应该将登录信息发送到目标,例如通过执行
curl --cookie-jar cookies.txt --form passphrase=test --form username=test http://example.com/login/target
Run Code Online (Sandbox Code Playgroud)
(请注意,通常不建议以这种方式在命令行中输入密码。您的密码可能存储在命令历史记录中,可能会被盗。)
该--cookie-jar选项告诉 curl 将所有 cookie 存储在一个文件中。如果登录成功并且服务器设置了会话 cookie,curl 会将它们保存在此文本文件中。
成功登录后,如果请求包含来自 cookie-jar 的 cookie,您应该能够访问 json 文件。这可以通过-b参数来实现 。如果-b不包含该=字符,curl 将使用文件内容作为 cookie。
curl -b cookies.txt http://example.com/home/apples.json -v
Run Code Online (Sandbox Code Playgroud)