我正在尝试使用netcat (nc)设置一个最小的web服务器。例如,当浏览器调用localhost:1500时,它应该显示一个函数的结果(在下面的示例中是date,但最终它将是一个python或c程序,它会产生一些数据)。我的小netcat web服务器需要是bash中的while true循环,可能就像这样简单:
while true ; do echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 ; done
当我尝试这样做时,浏览器会在nc启动时显示当前可用的数据。不过,我希望浏览器在请求数据时显示数据。我如何才能做到这一点?
发布于 2013-10-02 22:17:26
试试这个:
while true ; do nc -l -p 1500 -c 'echo -e "HTTP/1.1 200 OK\n\n $(date)"'; done
-c
使netcat在shell中执行给定的命令,因此您可以使用echo。如果不需要echo,可以使用-e
。有关这方面的更多信息,请尝试man nc
。请注意,在使用echo
时,您的程序( date
-replacement)无法获取浏览器请求。所以你可能最终想做这样的事情:
while true ; do nc -l -p 1500 -e /path/to/yourprogram ; done
其中yourprogram
必须做协议的事情,如处理GET,发送HTTP200等。
发布于 2013-05-20 06:40:24
在netcat
命令行中添加-q 1
:
while true; do
echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 -q 1
done
发布于 2013-08-07 01:12:39
您面临的问题是,nc不知道web客户端何时完成其请求,因此它可以响应请求。
web会话应该是这样的。
TCP session is established.
Browser Request Header: GET / HTTP/1.1
Browser Request Header: Host: www.google.com
Browser Request Header: \n #Note: Browser is telling Webserver that the request header is complete.
Server Response Header: HTTP/1.1 200 OK
Server Response Header: Content-Type: text/html
Server Response Header: Content-Length: 24
Server Response Header: \n #Note: Webserver is telling browser that response header is complete
Server Message Body: <html>sample html</html>
Server Message Body: \n #Note: Webserver is telling the browser that the requested resource is finished.
The server closes the TCP session.
以"\n“开头的行只是没有空格的空行,并且只包含一个换行符。
我的bash httpd是由xinetd,xinetd tutorial启动的。它还将日期、时间、浏览器IP地址和整个浏览器请求记录到日志文件中,并计算服务器标头响应的内容长度。
user@machine:/usr/local/bin# cat ./bash_httpd
#!/bin/bash
x=0;
Log=$( echo -n "["$(date "+%F %T %Z")"] $REMOTE_HOST ")$(
while read I[$x] && [ ${#I[$x]} -gt 1 ];do
echo -n '"'${I[$x]} | sed -e's,.$,",'; let "x = $x + 1";
done ;
); echo $Log >> /var/log/bash_httpd
Message_Body=$(echo -en '<html>Sample html</html>')
echo -en "HTTP/1.0 200 OK\nContent-Type: text/html\nContent-Length: ${#Message_Body}\n\n$Message_Body"
要添加更多功能,您可以合并。
METHOD=$(echo ${I[0]} |cut -d" " -f1)
REQUEST=$(echo ${I[0]} |cut -d" " -f2)
HTTP_VERSION=$(echo ${I[0]} |cut -d" " -f3)
If METHOD = "GET" ]; then
case "$REQUEST" in
"/") Message_Body="HTML formatted home page stuff"
;;
/who) Message_Body="HTML formatted results of who"
;;
/ps) Message_Body="HTML formatted results of ps"
;;
*) Message_Body= "Error Page not found header and content"
;;
esac
fi
痛击快乐!
https://stackoverflow.com/questions/16640054
复制相似问题