如何在收到服务器响应后关闭netcat连接?

8

我需要通过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比我能等待的时间要长,我需要尽快关闭连接。
2个回答

4

很不幸,-q标志对我没有起作用。 我使用的是“OpenBSD netcat(Debian修补程序级别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

惊人的答案。正是我在寻找的。 - robe007

1
你需要的是-q开关。如果你指定:

netcat -q 0 localhost 30002

netcat will exit immediately.


1
netcat v7.50 中没有此功能。 - karatedog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接