收到服务器响应后如何关闭netcat连接? [英] How to close netcat connection after receive a server response?

查看:58
本文介绍了收到服务器响应后如何关闭netcat连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 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

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

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.

推荐答案

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

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

这篇关于收到服务器响应后如何关闭netcat连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆