Automatic SSH-tunnel upkeeping

Needed automatic upkeep of SSH-tunnels. This script can be used to start SSH-tunnels at boot and also to keep them up by running service ssh-tunnels start periodically from example cron.

Here is the init.d-script itself:

/etc/init.d/ssh-tunnels

#!/bin/bash

#################################################
#################################################
# NOTE: Usually don't touch anything here       #
# rather modify /etc/ssh-tunnels.conf           #
#################################################
#################################################

# start or stop
start=0
stop=0

# files
CONF="/etc/ssh-tunnels.conf"

# parse rules
do_tunnels()
{
# get process information to identify already running tunnels
processes=`ps axo cmd | grep ssh`

echo "read tunnel definitions from $CONF..."
while read line; do
    if [ "${#line}" -lt "1" ]; then
        continue
    fi
    if [ "${line:0:1}" == "#" ]; then
        continue
    fi

	i=0
    for x in $line; do
        if [ "$i" -eq "0" ]; then
            host=$x
        elif [ "$i" -eq "1" ]; then
            user=$x
        elif [ "$i" -eq "2" ]; then
            port_local=$x
        elif [ "$i" -eq "3" ]; then
            port_remote=$x
        fi
        i=$((i+1))
    done

    if [ "$i" -lt "3" ]; then
        echo "invalid rule: $line"
        continue
    fi

	cmd="ssh -y -f -4 -N $user@$host -L $port_local:localhost:$port_remote"
	running=`ps axo pid,cmd | grep "$cmd" | grep --invert-match grep`

	if [ "$running" == "" ]; then
		if [ "$start" == "1" ]; then
			echo "Tunnel DOWN, start tunnel ($cmd)..."
			$cmd
		else
			echo "Tunnel DOWN ($cmd)..."
		fi
	else
		if [ "$stop" == "1" ]; then
			echo "Tunnel UP, stop tunnel ($cmd)..."
			pid=`echo $running | awk '{print $1;}'`
			kill $pid
			if [ "$start" == "1" ]; then
				echo "Restart tunnel ($cmd)..."
				$cmd
			fi
		else
			echo "Tunnel UP ($cmd)..."
		fi
	fi
done < $CONF
}


case "$1" in
  start)
		start=1
        do_tunnels
        ;;
  stop)
		stop=1
		do_tunnels
        ;;
  restart)
		stop=1
		start=1
        do_tunnels
        ;;
  status)
		stop=0
		start=0
		do_tunnels
        ;;
esac

Simple config for this script:
/etc/ssh-tunnels.conf

#
# Will do something like this:
# ssh -y -f -4 -N <user>@<host> -L <local port>:localhost:<remote port>
#
# Will also check if the tunnel is already up.
#
# host              user        local port  remote port
server2.tldr.fi     root        3307        3306
server2.tldr.fi     root        27017       27017

Remember to add example symbolic link to /etc/rc2.d/ to automatically start those tunnels at startup and something like this to example /etc/cron.hourly/sshtunnels to keep them up always:
/etc/cron.hourly/sshtunnels

#!/bin/bash
#
# start ssh-tunnels if they are down
#
service ssh-tunnels start

 

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 3 = 9