Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing netcat in bash

Tags:

bash

netcat

As the basis for a larger script I'm trying to write I'm trying to basically implement a basic netcat client in bash. My current script techincally works, it looks like this:

#!/bin/bash

exec 3<>/dev/tcp/$1/$2         

cat <&3 &                      
cat <&1 >3

The problem with it is that it leaves a hanging cat process which needs to be killed, but I can't figure an automatic way to do so, and manually running pkill cat doesn't really seem sporting.

like image 403
Mediocre Gopher Avatar asked Aug 24 '12 23:08

Mediocre Gopher


2 Answers

I've accepted Jeremy's answer as correct, but for anyone curious here's the full script I ended up with:

#!/bin/bash

exec 3<>/dev/tcp/$1/$2         

control_c()
{
    kill $CAT_PID
    exit $?
}

trap control_c SIGINT

cat <&3 &                      
CAT_PID=$!
cat >&3
like image 151
Mediocre Gopher Avatar answered Nov 02 '22 08:11

Mediocre Gopher


It is a horrid kludge, but you could spawn a subshell and so something like this:

CAT1_PID=$$
echo CAT1_PID > /tmp/CAT1_PID
exec cat <&3 &

Then, of course, you run into race conditions if more than one copy of this script happens to be running.

Depending on your shell, you may be able to call some form of exec and "rename" cat in the PS list. Then you can

pkill the_cat_that_ate_the_network
like image 22
Jeremy J Starcher Avatar answered Nov 02 '22 06:11

Jeremy J Starcher