简体   繁体   English

如何使用 Netcat 读取和处理 POST 请求

[英]How to read & handle POST requests with Netcat

I want to make a simple HTTP server with Bash & netcat, and have a problem with reading POST requests entirely - the last line is always missing.我想用 Bash 和 netcat 制作一个简单的 HTTP 服务器,并且在完全读取 POST 请求时遇到问题 - 最后一行总是丢失。

The server is started like this:服务器是这样启动的:

netcat -l -p 8080 -e ./ncserver.sh

The ncserver.sh , reduced to bare minimum which displays the problem: ncserver.sh ,减少到最低限度,显示问题:

#!/bin/bash

while read INPUT; do
    echo "Req line: $INPUT" >&2
done;

I use Postman to make requests to the server, and expect the script to dump entire request data to stderr.我使用 Postman 向服务器发出请求,并期望脚本将整个请求数据转储到 stderr。 The request is a simple JSON:请求是一个简单的 JSON:

{
    name: "Eugene",
    age: 34
}

Update: Raw postman request data:更新:原始邮递员请求数据:

POST /foo/bar HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 7f5a57a7-1664-e79c-2242-7ba6b638e260

{
    name: "Eugene",
    age: 34
}

In the server's output I get all the headers and request body which is missing the last line, the } .在服务器的输出中,我得到了缺少最后一行}所有标头和请求正文。 The same holds for other content types, such as multipart/form-data - last line is always missing.这同样适用于其他内容类型,例如multipart/form-data - 最后一行总是丢失。

Note: if I add an empty line after JSON, I can see the } in terminal output.注意:如果我在 JSON 之后添加一个空行,我可以在终端输出中看到}

I tried using cat /dev/stdin instead of read but get No such device or address .我尝试使用cat /dev/stdin而不是read但得到No such device or address

The question probably can be generalized as how do I read HTTP requests in correct binary form in Bash?这个问题可能可以概括为如何在 Bash 中以正确的二进制形式读取 HTTP 请求?

Try as below.尝试如下。

#!/bin/bash

while IFS= read -r INPUT || [ "$INPUT" ]; do
    echo "Req line: $INPUT" >&2
done;   

Point to notice.点注意。

IFS= is to preserve any indentation. IFS=是为了保留任何缩进。
-r is to prevent backslash interpretation. -r是为了防止反斜杠解释。
Check for INPUT : When read reaches the end-of-file instead of end-of-line it assigns variable but exits.检查INPUT :当read到达文件尾而不是行尾时,它会分配变量但退出。 hence, check if we have anything in INPUT .因此,请检查INPUT是否有任何内容。

Hello @x1n13y84issmd42你好@x1n13y84issmd42

Just in case you are still looking for a solution.. I had good results when trying the following:以防万一您仍在寻找解决方案.. 在尝试以下操作时,我取得了不错的结果:

#!/usr/bin/env bash

read -d } PAYLOAD;

Instead of parsing each line as they come, the "-d }" option makes read store everything that comes through stdin in PAYLOAD until it meets "}". “-d }”选项不是在每一行出现时解析它们,而是让 read 将通过 stdin 传入的所有内容存储在 PAYLOAD 中,直到遇到“}”。

You can then process $PAYLOAD} with jq for instance然后您可以使用 jq 处理 $PAYLOAD} 例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM