我需要通过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大于我可以等待的值,我需要尽快关闭连接
答案 0 :(得分:3)
很不幸,-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
答案 1 :(得分:0)
您要寻找的是-q
开关。如果您指定:
netcat -q 0 localhost 30002
netcat
将立即退出。