Created
November 21, 2013 02:13
-
-
Save en0/7574994 to your computer and use it in GitHub Desktop.
Using netcat to proxy a host.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env bash | |
PORT="${1}" | |
TARGET="${2}" | |
[ -z "${3}" ] && TPORT="${1}" || TPORT="${3}" | |
if [ -z "$1" ] || [ -z "$2" ]; then | |
echo "Usage: $0 <port> <target> [target port]" | |
exit 1 | |
fi | |
## Create TMP Directory to hold pid files and fifos | |
TMP="$(mktemp -d)" | |
FIN="${TMP}/in" | |
FOUT="${TMP}/out" | |
## Create FIFOs | |
mkfifo "$FIN" | |
mkfifo "$FOUT" | |
echo Created Temp Directory: ${TMP} | |
echo Logging Directory: ${LOGD} | |
echo ---------------------------------------- | |
echo Proxing Host: ${TARGET}:${TPORT} | |
echo Listening on: ${PORT} | |
echo ---------------------------------------- | |
## Signal handler for a clean exit. | |
function stop_proxy { | |
## Kill all processes in the PID files | |
for i in `ls ${TMP}/*.pid 2> /dev/null`; do | |
stop_pid "$(cat $i)" | |
done | |
## Dump the fifos and the tmp dir | |
rm -f "${FIN}" "${FOUT}" | |
rmdir ${TMP} | |
exit 0 | |
} | |
function stop_pid { | |
rm -f "${TMP}/${1}.pid" && kill $1 2> /dev/null | |
} | |
function store_pid { | |
## only create this if we have a valid PID | |
[ ! -z "${1}" ] && echo $1 > "${TMP}/${1}.pid" | |
} | |
## grab signal hander | |
trap 'stop_proxy' INT | |
while true; do | |
## start proxy intake and grap pid (fork) | |
nc -l -p $PORT < $FOUT | tee -a "${FIN}" | sed "s|^|CLIENT\||g" & | |
sleep 1 | |
CLIENT="$(jobs -p | tail -n1)" | |
store_pid $CLIENT | |
## start proxy forward and grab pid (fork) | |
nc "$TARGET" "$TPORT" < $FIN | tee -a "${FOUT}" | sed "s|^|SERVER\||g" & | |
SERV="$(jobs -p | tail -n1)" | |
store_pid $SERV | |
## Wait for -l to end | |
wait $CLIENT | |
## Clean up PID file | |
rm "${TMP}/${CLIENT}.pid" | |
## Stop other server connection | |
stop_pid $SERV | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment