utx*_*eee 7 windows webserver batch-file named-pipes netcat
我正在尝试仅使用Windows批处理脚本来设置Web服务器.
我已经提出了以下脚本:
@echo off
@setlocal enabledelayedexpansion
for /l %%a in (1,0,2) do (
type tempfile.txt | nc -w 1 -l -p 80 | findstr mystring
if !ERRORLEVEL! == 0 (
echo found > tempfile.txt
) else (
echo not-found > tempfile.txt
)
)
Run Code Online (Sandbox Code Playgroud)
但是,响应始终是一个请求,我的意思是,如果我在浏览器中键入这样的内容:
REQUEST: localhost/mystring
Run Code Online (Sandbox Code Playgroud)
我会得到以下回复:
RESPONSE: not-found
Run Code Online (Sandbox Code Playgroud)
只有在下一个请求中,我才能收到上述请求的正确答案.
发生这种情况是因为一旦netcat收到请求,它就会响应tempfile.txt的当前内容,该内容尚未根据请求进行更新.
有没有办法阻止响应,直到tempfile.txt更新或任何其他方法达到预期的结果?
签出-e
选项,您可以编写一个执行处理然后执行的脚本
nc -L -w1 -p 80 -eexec.bat
Run Code Online (Sandbox Code Playgroud)
它会将stdin和stdout从nc来回传递给你想要的脚本.
exec.bat可能是(有点伪代码):
findstr mystring
if not errorlevel 1 (echo found) else (echo not-found)
Run Code Online (Sandbox Code Playgroud)
或者一个循环(也有点伪代码):
:top
set /p input=
if input wasn't "" echo %input% >> output.dat && goto top
findstr /C:"mystring" output.dat
if not errorlevel 1 (echo found) else (echo not-found)
Run Code Online (Sandbox Code Playgroud)
据我所知,问题是nc
无法执行回调来根据客户端输入定制其输出。一旦你有...
stdout generation | nc -l
Run Code Online (Sandbox Code Playgroud)
...阻塞并等待连接,其输出已经确定。该输出此时是静态的。
我想到的唯一解决方法效率相当低。其基本涉及以下逻辑:
示例代码:
@echo off & setlocal
rem // macro for netcat command line and args
set "nc=\cygwin64\bin\nc.exe -w 1 -l 80"
rem // macro for sending refresh header
set "refresh=^(echo HTTP/1.1 200 OK^&echo Refresh:0;^)^| %nc%"
for /L %%# in (1,0,2) do (
rem // run refresh macro and capture client's requested URL
for /f "tokens=2" %%I in ('%refresh% ^| findstr "^GET"') do set "URL=%%I"
rem // serve content to the client
setlocal enabledelayedexpansion
echo URL: !URL! | %nc%
endlocal
)
Run Code Online (Sandbox Code Playgroud)
附带说明一下,如果在设置时启用了延迟扩展,则可能会破坏用感叹号设置的变量值。最好等到检索后再启用延迟扩展。
此外,在执行布尔检查时,使用条件执行%ERRORLEVEL%
会更优雅。但这与我的解决方案无关。:)
最后,type filename.html | nc -l
考虑使用<filename.html nc -l
(或nc -l <filename.html
) 来避免无用地使用 ,而不是执行type
。