【问题标题】:run a command conditionally with netcat and grep使用 netcat 和 grep 有条件地运行命令
【发布时间】:2013-08-02 03:25:13
【问题描述】:

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

到目前为止我有这个;

netcat -lk 12345 | grep "Keep-Alive"

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

它需要在 crontab 中运行...

感谢您的帮助!

【问题讨论】:

  • 您希望多久收听一次传入的请求?

标签: linux bash grep command netcat


【解决方案1】:

这个怎么样?

    #!/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”命令替换为您要执行的脚本。

【讨论】:

  • 超级!,就是这样!,非常感谢。我在 crontab 中需要两个这样的脚本,没问题吧?
  • @Lectere 完全没问题,在 if 块中你可以添加你需要的所有命令。
  • if [[ $line =~ Keep-Alive ]]; then ... fi 应该也能正常工作
  • 还有if echo "$line" | grep -q 'Keep-Alive'; then
【解决方案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.

【讨论】:

  • 嗯..这也是我更喜欢的。因此添加了答案。否则,@wooghie 的回答同样好。 :)
【解决方案3】:

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

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

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

404file.txt 的位置有 HTTP/1.1 404 未找到文件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    相关资源
    最近更新 更多