直接用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请求的终极指南

相关推荐
IMPYLH8 分钟前
Linux 的 wc 命令
linux·运维·服务器·前端·bash
pengyi8710155 小时前
HTTP代理抓包核心原理,全面读懂请求与响应数据逻辑
网络·网络协议·http
yqcoder7 小时前
HTTP 进化论:从“单车道土路”到“磁悬浮列车”
网络·网络协议·http
小短腿的代码世界7 小时前
QHttpEngine深度解析:Qt嵌入式HTTP服务端的工业级架构与性能调优
qt·http·架构
pengyi8710158 小时前
HTTP代理抓包实操教程,零基础监控IP请求与响应数据
网络协议·tcp/ip·http
Soari8 小时前
【紧急发布】Claude Code v2.1.148 :修复 Bash 127 瘫痪 Bug,/simplify 升级为 AI 代码评审
人工智能·bug·bash·claudecode
yqcoder1 天前
数据的“包装方式”:深入解析 HTTP Content-Type
网络·网络协议·http
s_w.h1 天前
【 linux 】认识make和makefile
linux·运维·bash
wu@555551 天前
使用acme生成免费https泛域名证书(通配符证书)
网络协议·http·https
wljt1 天前
为什么要使用Spring Cloud,而不是HTTP直接调用接口?
spring·http·spring cloud