curl是利用URL语法在命令行方式下工作的开源文件传输工具。也可以用来测试端口的连通性,具体用法:
curl [option] [url]
说明:
ip:是测试主机的ip地址
port:是端口,比如80
如果远程主机开通了相应的端口,都会输出信息,如果没有开通相应的端口,则没有任何提示,需要CTRL+C断开。
1、获取页面内容,当我们不加任何选项使用 curl 时,默认会发送 GET 请求来获取链接内容到标准输出。
[root@iZbp1hxhb6bx0cij7b4b7Z ~]# curl www.cloudduo.cn
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
2、如果我们只想要显示 HTTP 头,而不显示文件内容,可以使用 -I 选项:
[root@VM-16-5-centos ~]# curl -I www.cloudduo.cn
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Sat, 06 Nov 2021 06:37:56 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
Location: https://www.cloudduo.cn/
Strict-Transport-Security: max-age=31536000
也可以同时显示 HTTP 头和文件内容,使用 -i 选项:
[root@VM-16-5-centos ~]# curl -i https://www.baidu.com
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: keep-alive
Content-Length: 2443
Content-Type: text/html
Date: Sat, 06 Nov 2021 06:48:18 GMT
Etag: "58860402-98b"
Last-Modified: Mon, 23 Jan 2017 13:24:18 GMT
Pragma: no-cache
Server: bfe/1.0.8.18
Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div </html>
3、使用 -L 跟随链接重定向
如果直接使用 curl 打开某些被重定向后的链接,这种情况下就无法获取我们想要的网页内容。例如:
curl -L www.cloudduo.cn
4、使用 -A 自定义 User-Agent
我们可以使用 -A 来自定义用户代理,例如下面的命令将伪装成安卓火狐浏览器对网页进行请求:
curl -A "Mozilla/5.0 (Android; Mobile; rv:35.0) Gecko/35.0 Firefox/35.0" https://www.baidu.com
下面我们会使用 -H 来实现同样的目的。
5、使用 -H 自定义 header
当我们需要传递特定的 header 的时候,可以仿照以下命令来写:
curl -H "Referer: www.example.com" -H "User-Agent: Custom-User-Agent" http://www.baidu.com
可以看到,当我们使用 -H 来自定义 User-Agent 时,需要使用 "User-Agent: xxx" 的格式。
我们能够直接在 header 中传递 Cookie,格式与上面的例子一样:
curl -H "Cookie: JSESSIONID=D0112A5063D938586B659EF8F939BE24" http://www.example.com
6、把链接页面的内容输出到本地文件中
curl https://www.baidu.com > index.html