bash 使用 netcat 和 grep 有条件地运行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17990099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:05:46  来源:igfitidea点击:

run a command conditionally with netcat and grep

linuxbashgrepcommandnetcat

提问by Lectere

I need netcat to listen on incomming HTTP requests, and depending on the request, I need to run a script.

我需要 netcat 来监听传入的 HTTP 请求,并且根据请求,我需要运行一个脚本。

So far I have this;

到目前为止,我有这个;

netcat -lk 12345 | grep "Keep-Alive"

So every time netcat recieves a package that contains a "keep-alive", I need to fire a script.

所以每次 netcat 收到一个包含“keep-alive”的包时,我都需要触发一个脚本。

It needs to run in the crontab...

它需要在 crontab 中运行...

Thanks for your help!

谢谢你的帮助!

回答by wooghie

How about this?

这个怎么样?

    #!/bin/bash

    netcat -lk -p 12345 | while read line
    do
        match=$(echo $line | grep -c 'Keep-Alive')
        if [ $match -eq 1 ]; then
            echo "Here run whatever you want..."
        fi
    done

Replace the "echo" command with the script you want to execute.

将“echo”命令替换为您要执行的脚本。

回答by anishsane

How about:

怎么样:

#!/bin/bash
netcat -lk -p 12345 | grep 'Keep-Alive' | while read unused; do
    echo "Here run whatever you want..."
done

Or

或者

#!/bin/bash
netcat -lk -p 12345 | sed -n '/Keep-Alive/s/.*/found/p' | xargs -n 1 -I {} do_something
# replace do_something by your command.

回答by Burns Fisher

Depending on what you have on the client side, it might sit there waiting for netcat/the server to respond.

根据您在客户端的内容,它可能会坐在那里等待 netcat/服务器响应。

I did a similar thing to the above but used

我做了与上面类似的事情,但使用了

while true do
   netcat -l 1234 < 404file.txt

Where 404file.txthas HTTP/1.1 404FILE NOT FOUND

哪里404file.txtHTTP/1.1 404文件未找到

This disconnects the client and since netcathas no 'k' it terminates and restarts because of the while true, all ready to receive and send the 404 again.

这会断开客户端的连接,并且由于netcat没有“k”,它会因为 while 为真而终止并重新启动,所有准备好再次接收和发送 404。