Wednesday 25 September 2013

Script for AutoReverse Tunneling

#/bin/bash
# Uncomment the set -x line to debug
#set -x
#############################
###       VARIABLES       ###
#############################
#
# What port is going to be used for the tunnel?  This should be unique to the PFG
TUNNELPORT="8035"
#
# What is the tunnel username?
TUNNELUSER="testuser"
#
# Where is the tunnel server located at? (IP or hostname if DNS is setup)
TUNNELSERVER="server2.ctechz.com"
#
# What port is the tunnel server listening on? (This is common amongst all of the PFGs, typically 22999)
# To get changed with 247
TUNNELEXTPORT="22999"
#
# What directory is the key stored in?
KEYLOC="/root/.ssh"
#
# What is the file name that the key is using?
KEYNAME="ReverseTunnelKey-Port_$TUNNELPORT"

#########################################################################################################
####### Do not edit below this line ######################################
#########################################################################################################
SSH=`which ssh`
KEYGEN=`which ssh-keygen`
#
#############################
###   Let's get to work   ###
#############################
#
### Check that the key exists and if it does not, then create it and copy it over
if [ ! -e $KEYLOC/$KEYNAME ]
then
    $KEYGEN -b 4096 -t rsa -N "" -f ~/.ssh/$KEYNAME
 

    ssh -p $TUNNELEXTPORT $TUNNELUSER@$TUNNELSERVER "if [ ! -d ~/.ssh ]; then mkdir ~/.ssh; touch ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys; fi"

    scp -P $TUNNELEXTPORT ~/.ssh/$KEYNAME.pub $TUNNELUSER@$TUNNELSERVER:~/.ssh/
 

    ssh -p $TUNNELEXTPORT $TUNNELUSER@$TUNNELSERVER "cat ~/.ssh/$KEYNAME.pub >> ~/.ssh/authorized_keys"
fi
#
### Check to see if the tunnel is present
TunnelPres=`ps aux | grep "$TUNNELPORT:localhost:22 $TUNNELUSER@$TUNNELSERVER -p $TUNNELEXTPORT" | grep -v grep`
 

if [ -z "$TunnelPres" ]
then
#
### If absent, establish tunnel
echo "Establishing Reverse Tunnel"
    $SSH -i $KEYLOC/$KEYNAME -f -N -C -R $TUNNELPORT:localhost:22 $TUNNELUSER@$TUNNELSERVER -p $TUNNELEXTPORT 'top'
else
#
### If present do nothing and exit
    echo "Already established... doing nothing"
    exit 0
fi

No comments:

Post a Comment