简体   繁体   中英

How to close netcat connection after receive a server response?

I need to sendo a lot of messages via netcat or something similar. The problem is that when I run echo "something" | netcat ip port echo "something" | netcat ip port the connection continues opened after I received the response. Actually the connection continues opened waiting for a new input. However, what I need is that the connection closed after I receive the response. Look, my script is basically this:

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

If I can close the connection after print the response in result, everything will work fine. I know that there is an option -w "x" that closes the connection after "x" seconds, but the minimum value for "x" is 1 and 1 is bigger than I can wait, I need close the connection as soon as possible.

Unfortunately, the -q flag didn't work for me. I'm using "OpenBSD netcat (Debian patchlevel 1.187-1ubuntu0.1)" and, even though the -q flag shows up in the manual, it didn't work as mentioned in cnicutar's answer.

Therefore, my workaround was:

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

What you're looking for is the -q switch. If you specify:

netcat -q 0 localhost 30002

netcat will exit immediately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM