直接用Bash发送HTTP请求 —— 筑梦之路

bash 复制代码
追踪命令执行

strace -e trace=network,open,close bash -c 'exec 3<>/dev/tcp/example.org/80'

关键部分

socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) = 3
connect(3, {sa_family=AF_INET, sin_port=htons(80), sin_addr=inet_addr("93.184.215.14")}, 16) = 0

检查文件描述符

ls -lat /proc/self/fd/

lrwx------ 1 user user 64 Aug 25 15:01 0 -> /dev/pts/0
lrwx------ 1 user user 64 Aug 25 15:01 1 -> /dev/pts/1
lrwx------ 1 user user 64 Aug 25 15:01 2 -> /dev/pts/2
lrwx------ 1 user user 64 Aug 25 15:01 3 -> 'socket:[2910856]'
lr-x------ 1 user user 64 Aug 25 15:01 4 -> /proc/1579316/fd

3是连接到example.org的套接字的文件描述符

重点来了:

exec 3<> /dev/tcp/...这个语法。它的含义是: "创建一个用于输入和输出操作的套接字,并将其分配给进程标识符为3的文件描述符。


发送http请求

echo -ne "GET / HTTP/1.1\r\nHost: example.org\r\n\r\n" >&3

读取响应结果

cat <&3

HTTP/1.1 200 OK
Age: 243157
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Sun, 25 Aug 2024 14:15:54 GMT
Etag: "3147526947+ident"
Expires: Sun, 01 Sep 2024 14:15:54 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: ECAcc (dcd/7D77)
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 1256

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    ...
</head>
<body>
    <div>
        <h1>Example Domain</h1>
        <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p>
        <p><a href="https://www.iana.org/domains/example">More information...</a></p>
    </div>
</body>
</html>


关闭套接字

exec 3<&-

搜集来自掌握Bash的秘密:直接用Bash发送HTTP请求的终极指南

相关推荐
坐怀不乱杯魂38 分钟前
Linux 网络 - HTTP -cookie session
网络·网络协议·http
岚天start1 天前
Python HTTP服务器添加简单用户名密码认证的三种方案
服务器·python·http
ps酷教程1 天前
HttpPostRequestEncoder源码浅析
http·netty
Marshmallowc1 天前
强缓存失效了怎么办?深度解析浏览器内存缓存与硬盘缓存的存储逻辑
http·缓存·浏览器原理
Marshmallowc1 天前
为什么 Webpack 要打包?从 HTTP/1.1 限制到 HTTP/2 多路复用原理详解
前端·http·webpack
星辰徐哥1 天前
易语言网络通信编程基础:HTTP/HTTPS/TCP/UDP实战开发
开发语言·http·https·udp·tcp·易语言
DevilSeagull1 天前
HTTP/HTTPS数据包拓展
网络·网络协议·http·https·web渗透·we
码农水水1 天前
从 OpenFeign 到 RestClient:Spring Cloud 新时代的轻量化 HTTP 调用方案
java·运维·后端·spring·http·spring cloud·面试
REDcker1 天前
HTTP 状态码清单大全
网络·网络协议·http
dingdingfish2 天前
GNU Parallel 学习 - 第1章:How to read this book
bash·shell·gnu·parallel