用 SHELL 做个静态 HTTP 服务器
[日期:2011-12-27]
来源:Linux社区
作者:macintosh
[字体:大 中 小]
#!/bin/bash
#########################################################################################################
# 这是一个可以用来做静态 HTTP 的 BASH 脚本。 在 inetd/xinetd 中运行就可以了。
# 对于 php 内容,通过调用 php 命令可以实现完整的 http + php 功能。 Good!
#########################################################################################################
DECODEURL()
{
echo "$1" | \
awk 'BEGIN {
for (i=0;i<=16;i++) hex[sprintf("%X",i)]=i;}
{ for (i=1;i<=length($0);i++)
{ c=substr($0,i,1)
if (c=="+") printf (" ");
else if (c=="%") {
printf ("%c",hex[substr($0,++i,1)]*16+hex[substr($0,++i,1)])
}
else printf (c);
}
} '
}
LANG=en_US.UTF-8
httprootconf=/tmp/httproot
read GET eURL HTTPVER
URL=$(DECODEURL "$eURL")
URI="$URL"
[ -f "${httprootconf}" ] && URL="$( cat "${httprootconf}" )$URL"
# Get HTTP Header
lines=$( awk '{if ($0 == "\r") exit; else{ print ; print "\n" }}')
#Get Ranges
RANGE=$( echo -e "$lines" | sed 's/\r//g'| ( while read eRange Range ; do if [ "$eRange" = "Range:" ] ; then echo $Range ; exit ; fi ; done ) )
RANGE=$( echo "$RANGE" | awk -F"=" '{print $2}')
RANGE_A=$( echo "$RANGE" | awk -F"-" '{print $1}')
RANGE_B=$( echo "$RANGE" | awk -F"-" '{print $2}')
#Get Host
HOST=$( echo -e "$lines" | sed 's/\r//g'| ( while read eHOST HOST ; do if [ "$eHOST" = "Host:" ] ; then echo $HOST ; exit ; fi ; done ) )
if [ -e "$URL" ] ; then
echo -ne "HTTP/1.1 200 OK\r\n"
else
echo -ne "HTTP/1.1 404 Not Found\r\n"
fi
echo -ne "HTTP/1.1 200 OK\r\n"
echo -ne "Server: microcai's Very Simple HTTP index list Script\r\n"
echo -n "Data:" ; date
echo "URL: $URL"
if [ -d "$URL" ] || [ ! -e "$URL" ] ; then
echo "Content-Type: text/html"
else
filelength=$(ls -l "$URL" | awk '{print $5}')
contentlength=${filelength}
echo -n "Content-Type:"
file -b --mime-type "$URL"
echo -n "Content-Length: "
range_b="${RANGE_B}"
if [ -n "${RANGE}" ] ; then
[ -z "${RANGE_B}" ] && range_b="${filelength}"
contentlength=$( echo "${range_b} - ${RANGE_A}" | bc )
fi
echo ${contentlength}
#Content-Range: bytes 4506080-7009200/7009201
echo -ne "Content-Range: bytes $[RANGE_A]-$[range_b-1]/${filelength}\r\n"
fi
echo -e "Connection: close\r\n"
if [ -d "$URL" ] ; then
echo "
Directory /"
echo "
Directory listing of $URI
- "
echo "
../"for files in "$URL"/*
do
filename=$( basename "$files" )
if [ -d "$files" ] ; then
echo "
${filename}/"else
echo "
${filename}"fi
done
echo -ne "
Microcai Simple HTTP Server by BASH, `date`
Copyright 2011; Microcai
"
elif [ -f "$URL" ] ; then
if [ -z "${RANGE}" ] ; then
cat "$URL"
elif [ -z "${RANGE_B}" ] ; then # dd 性能不好 , 但是为了支持 XX ,无奈
dd if="$URL" ibs=1 skip=${RANGE_A} count=${contentlength}
else
tail -c "+$[RANGE_A+1]" "$URL"
fi
else
echo "Listen to Microcai, the file is really not found! goto Root Index"
fi