How to close netcat connection after receive a server response? - bash

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

Related

Test if netcat listener got a connection and run a command locally

I need a way to fire a netcat listener from a shell script and if a connection received I need to run a command on the same local listener machine and without interrupting the netcat process / connection
it's like the -e option but I need to run a command locally while keeping the netcat connection running
I don't really know if it can be done I mean after the shell process forked the netcat child can it interact with nc's output for example and run other command before netcat exit?
Edit: I figured it's even easier to do it on the client C code side by checking the return value of an initial send() message to determine if the client connected successfully if we got the sent message length
sret = send(sock, message, strlen(message), 0);
if (sret == strlen(message)) // We're Connected
do something
Thanks
This will check if the initial nc process has started listening, and it will echo every line of input it receives and will then send back a Received response:
rm -f input.txt
touch input.txt
tail -f input.txt | nc -l 5555 > output.txt &
if ! ps -p $! >/dev/null; then
echo "Netcat didn't start. Exiting..."
exit 1
fi
tail -f output.txt | while read -r LINE; do
echo "Received input: $LINE"
echo "Received" >> input.txt
done
See if you can adapt this to meet your needs.

Forked init.d process becomes unresponsive

I have a script to start and fork a netcat process. After a while, the netcat process stops logging output. Remote computers are supposed to connect to the socket and send a message every few hours, but it seems like the netcat process dies/halts after a while, because there's usually only one message from the remotes on the hour after the daemon starts, and then no more follow. I ensured it wasn't a problem with the remotes not sending their information to the socket; so it seems like something to do with the netcat process dying out. When I run atop, the process is still alive, but if I try to connect to the socket manually and send something, it doesn't log it to the output file.
dstart(){
if [ -f /run/mynetcat.pid ]; then
echo "Netcat instance running on "$(cat /run/mynetcat.pid)
exit 1
else
echo "Starting Netcat instance"
mkdir -p /var/log/mynetcat/
(setsid nc -l -k -p 25001 >> /var/log/mynetcat/mynetcat.log 2> /var/log/mynetcat/mynetcat.err & echo $! > /run/mynetcat.pid)&
return 0
fi
}
###later on in the script
case "$1" in
start)
dstart
;;

I want to open a netcat connection and keep sending some text forever

echo " The NC send commands on port 2612"
while :
do
echo "hello " | nc -q -1 <some IP> 2612
done
I want open a netcat session forever, and that is been achived by -q -1.
How can I send "hello" on the same channed in every 20 second.
my earlier script was as following, but that opens nc connection every time.
What I really want is to open connection once and send "echo hello" evey 20 sec.
while :
do
echo "hello " | nc 192.168.100.161 2612
sleep 20
done
while echo "hello"; do
sleep 20
done | nc -q 192.168.100.161 2612
Note that we moved the echo into the condition of the loop, so that we stop trying to run it if nc exits (causing the echos to fail).
If you want to be able to retain state (for instance, a counter) from inside the loop and access it after the pipeline exited, then things need to change a bit further:
#!/bin/bash
# ^^^^- process substitutions aren't part of POSIX sh
count=0
while echo "hello"; do
(( ++count ))
sleep 20
done > >(nc -q 192.168.100.161 2612)
echo "Ran $count loops before exiting" >&2
There, the redirection is done as a process substitution, and the loop takes place inside the same shell instance that continues after it exits. See BashFAQ #24 for more details on this problem and solution.

How can I terminate netcat so my script can loop again?

I'm running a bash script that goes through the list of my remote server IPs, connects via netcat (telnet) for each line, and runs a few commands.
The problem is I can't seem to figure out how to terminate netcat so the script can loop to the next IP in the list.
Here's the relevant bit:
#!/bin/bash
while ISF= read -r line;do
(
sleep 3
printf 'command1'
sleep 3
printf 'command2'
sleep 3
) | nc $line
done < ~/servers.txt
The remote servers don't send an EOF, so is there something I can echo or printf at netcat to terminate netcat so the script can loop through again? I would really rather not do a -w flag for a timeout, because I have quite a few servers I need to do this on, and a timeout would make it take much longer.
Specify a timeout after which nc will exit if it receives no further input, either from the remote end or via standard input.
... | nc "$line" -w 10 # Choose a value for -w as appropriate
Depends on your version of netcat, but -c should do what your looking for. From the usage statement of gnu netcat (which is likely what you're running on Ubuntu):
-c, --close close connection on EOF from stdin

Handling input from script piped to netcat

I have a system that handles incoming emails to send them to a blackbox application at my job. The high level script is maintained by inittab to always run and runs a child script to do the actual work with this command:
$SCRIPT | nc -l -p $PORT
The script itself reads from a named pipe, does a bit of parsing and processing of the data before calling echo to shuffle the data back through netcat to the process connected on $PORT.
What I need is some method to handle incoming data from the far end of my pipe. When I make a request within the application to close the connection it sends back a string (I can define it to whatever I want) and waits for my script to close the pipe. I currently am struggling to understand how I can add in the functionality to read incoming data from the other end; verify it is the command to close the pipe, and then exit the script.
My script (in a nutshell) looks like this:
while true ; do
email_input="`cat "$pipe"`"
if [[ $email_input =~ .*escape_queue.* ]] ; then
break;
fi
echo "`parse`"
done
I'm open to the possibility of having to alter the program flow, I just can't wrap my head around how I would be able to read the data incoming asynchronously since the script blocks on cat $pipe until a new email is received to process.
If its not clear, I'm at a novice level with bash scripting and am always open to suggestions for improvement.
UPDATE
I've changed my script call to
$SCRIPT | nc -l -p $PORT > $nc_data
and within the script itself
netcat_response="`cat "$nc_data"`";
if [[ "$netcat_response" =~ "exit" ]] ; then
cat /dev/null > $nc_data
break;
fi
At this point the script terminates once a new message is piped into the fifo. This means that I will always lose 1 message as it gets read by the script and then the script terminates. The script still blocks on the cat until something is read. Worst case scenario this will have to do.
You can have nc quit after a certain time from the EOF of stdin.
$SCRIPT | nc -l -q 5 -p $PORT > $nc_data
-q being the option to quit after a certain amount of seconds.

Resources