如何在无额外软件的Linux机器上用单行命令启动返回JSON的HTTP服务器
单行命令启动返回JSON的HTTP服务器
以下是几种无需额外安装软件、适用于基础Linux机器的单行命令,均可返回指定JSON内容(以{"OK": true}为例):
Python 3 实现(最通用)
利用Python3自带的http.server模块自定义请求处理器,无需额外依赖:
python3 -c 'from http.server import BaseHTTPRequestHandler, HTTPServer; class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(b'{"OK": true}'); HTTPServer(("",8080), Handler).serve_forever()'
- 访问任意路径都会返回JSON响应
- 自动设置正确的
Content-Type头,状态码200
Netcat(nc)实现(几乎全平台兼容)
通过循环让nc持续监听端口,每次请求返回HTTP响应:
GNU Netcat版本
while true; do nc -lp 8080 -c 'echo -e "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"OK\": true}"'; done
OpenBSD Netcat版本(部分发行版默认)
while true; do nc -l 8080 -c 'echo -e "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"OK\": true}"'; done
- 依赖系统自带的nc工具,无需额外安装
- 每次连接后nc会退出,循环保证持续服务
Busybox 实现(轻量/嵌入式系统)
如果机器预装Busybox,可使用tcpsvd或httpd工具:
用tcpsvd持续监听
tcpsvd -v 0.0.0.0 8080 sh -c 'echo -e "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"OK\": true}"'
用httpd配置自定义响应
busybox httpd -f -p 8080 -c <(echo -e "*.json:\n content_type: application/json\n handler: echo '{\"OK\": true}'")
- 适合嵌入式Linux、Alpine等轻量系统
Node.js 实现(若系统预装)
如果机器已安装Node.js,可快速启动服务器:
node -e "require('http').createServer((req,res)=>{res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify({OK:true}));}).listen(8080)"
内容的提问来源于stack exchange,提问作者Neil
相关产品推荐
相关产品推荐

