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

问题描述 投票:2回答:3

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

到目前为止,我有这个;

netcat -lk 12345 | grep "Keep-Alive"

因此,每当netcat收到一个包含“ keep-alive”的软件包时,我都需要触发一个脚本。

它需要在crontab中运行...

感谢您的帮助!

linux bash grep command netcat
3个回答
8
投票

怎么样?

    #!/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

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


2
投票

怎么样:

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

#!/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.

0
投票

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

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

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

404file.txtHTTP/1.1 404文件未找到的地方

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

© www.soinside.com 2019 - 2024. All rights reserved.