【问题标题】:How to close netcat connection after receive a server response?收到服务器响应后如何关闭netcat连接?
【发布时间】:2019-06-12 20:05:06
【问题描述】:

我需要通过 netcat 或类似的方式发送大量消息。问题是当我运行echo "something" | netcat ip port 时,在收到响应后连接继续打开。实际上连接继续打开等待新的输入。但是,我需要的是在收到响应后连接关闭。看,我的脚本基本上是这样的:

#!/bin/bash
i=1
while [ $i -ne 10000 ];do
    sed -n $[i]p wordlist | netcat localhost 30002 >> result
    i=$[$i+1]
done

如果我可以在打印结果后关闭连接,那么一切都会正常。我知道有一个选项 -w "x" 可以在 "x" 秒后关闭连接,但是 "x" 的最小值是 1 并且 1 比我可以等待的要大,我需要尽快关闭连接.

【问题讨论】:

    标签: bash tcp server client netcat


    【解决方案1】:

    您正在寻找的是-q 开关。如果您指定:

    netcat -q 0 localhost 30002
    

    netcat 将立即退出。

    【讨论】:

    • 这在 netcat v7.50 中不可用
    【解决方案2】:

    不幸的是,-q 标志对我不起作用。 我正在使用“OpenBSD netcat (Debian patchlevel 1.187-1ubuntu0.1)”,尽管手册中出现了-q 标志,但它并没有像 cnicutar 的回答中提到的那样工作。

    因此,我的解决方法是:

    #!/bin/sh
    
    # POSIX COMPLIANT
    
    HOST="localhost"
    PORT=30002
    
    scan () {
        # Ensuring there is no file named msg
        rm msg
    
        # While msg file doesn't exist or is empty, do
        while [ ! -s msg ]; do
            # Remove instruction from within the loop
            rm msg
    
            # Append the received messages to msg file, and put the process in the background
            echo "$HOST $PORT" | xargs nc >> msg &
    
            # If the file exists and is not empty, return, we received the message
            [ -s msg ] && return;
    
            # A small timeout.. doing some tests I noticed that a timeout of zero sometimes didn't work to catch the message
            # Maybe nc needs a small time to receive everything. You might want to test and increase or decrease this timeout if needed.
            sleep 0.1
    
            # This script will be spawning a lot of nc process, to kill it before the loop runs again
            pkill -x nc
        done
    } 2> /dev/null 
    
    scan
    
    # The function returned, so cat the file
    cat msg
    
    # make sure nc is killed
    pkill -x nc > /dev/null 2>&1
    rm msg
    

    【讨论】:

    • 惊人的答案。正是我想要的。
    猜你喜欢
    • 2020-05-15
    • 2014-09-08
    • 2018-11-04
    • 2019-05-22
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多