[Gllug] ssh to a machine behind NAT

Peter Joanes pjoanes at hotmail.com
Thu Jan 26 13:12:55 UTC 2006


On Thursday 26 January 2006 04:22, Paul Rayner wrote:
> My plan for allowing remote admin is to machine 1 is as follows:
>
> Set up a cron task to run every 5 mins which will see if there is an
> ssh connection to machine 2, and if not it will establish one,
> forwarding a port from the local machine to the remote one. I will then
> connect to machine 2 and connect to the forwarded port.
>
> Surely there is a neater way to achieve this? The method above seems
> like a bit of a kludge to me.

That is how I felt when I made the script below a couple of years ago to do 
the same thing. It was for a Cygwin machine that didn't have cron. I found 
that it was necessary to kill any stale sshd processes on "machine 2", and to 
have a minimum time before retrying in case machine 2 is unreachable. (It is 
intentional that the logic for working out how long to wait is slightly 
redundant, in case of an error in the string processing).

Regards,
	Pete.


#!/bin/bash
#
# ssh_keep_open.sh - Keep ssh forwarding connection open.
# depends on: bash, ssh, tail, cut, dc, sleep, rev
# assumes ssh login on remote host is password-less.

REMOTE_HOST="user at machine2.wherever"
REMOTE_PORT=2222
LOCAL_PORT=22
MIN_TIME_SECS=600       # Minimum time between reconnections
SSH_OPTS="-o ServerAliveInterval=60"

LAST_SSHD_PIDS=""

export TIMEFORMAT="%0R"

while [ 1 ]
do
        if [ -n "$LAST_SSHD_PIDS" ]
        then
             ssh $SSH_OPTS $REMOTE_HOST "kill $LAST_SSHD_PIDS"
        fi

        SPT="`(time ssh $SSH_OPTS $REMOTE_HOST -qR $REMOTE_PORT:localhost:
$LOCAL_PORT \
             'echo $PPID $$;exec sleep 7d') 2>&1`"

        LSPTEMP="`echo -n $SPT" " |rev |cut -d " " -f 3- |rev`"
        if [ -n "LSPTEMP" ]; then LAST_SSHD_PIDS="$LSPTEMP"; fi

        ST="`echo -n $SPT |rev |cut -d " " -f 1 |rev`"

        if [ $ST -lt $MIN_TIME_SECS ]
        then
                WAIT_TIME="`dc -e "$MIN_TIME_SECS $ST -n"`"
        elif [ $ST -ge $MIN_TIME_SECS ]
        then
                WAIT_TIME=0
        else
                WAIT_TIME="$MIN_TIME_SECS"
        fi
        sleep $WAIT_TIME
done
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list