#!/bin/bash scriptName=$(basename $0) version=0.1 idx=0 killFlag=0 localServiceIp="192.168.105.100" remoteIp="172.26.123.156" endpoint="192.168.105.100" user="$USER" cacheFile=.tunLast privateKeyLoc="~/.ssh/id_ed25519" override=0 debug=0 local="R" fromPort=0 toPort=0 function killTunnel { if [[ debug -eq 1 ]]; then printf "killTunnel %d\n" $toPort fi pkill -f "ssh -i ${privateKeyLoc} -fN${local} $toPort:" } function openTunnel { ssh -i ${privateKeyLoc} -fN${local} $toPort:${endpoint}:$fromPort ${user}@${remoteIp} } function parsePort { local delimiter=":" str=$1 fromPort=${str%%${delimiter}*} toPort=${str#*${delimiter}} if [[ ${#toPort} -eq 0 ]]; then toPort=$fromPort fi } function usage { echo " Usage: $scriptName [OPTIONS] Options: -k | --kill Try to kill defined tunnels, if missing will try to create them -p | --port FROM:TO Define new port forwarding rule, if in format FROM:TO - will create tunnel from port FROM on defined endpoint to port TO on local -u | --user USERNAME Define the user name on behalf of who will try to connect to remote target " } function about { echo " ${scriptName} ver.${version} Setup with next settings: started up under user: ${user} endpoint: ${endpoint} cacheFile: ${cacheFile} " } while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in -a | --about ) about exit ;; -u | --user ) shift; user=$1 ;; -l | --local ) local="L" remoteIp="localhost" ;; -k | --kill ) killFlag=1 ;; -p | --port ) shift; port[$idx]=$1 idx=$(($idx+1)) override=1 ;; -d | --debug ) debug=1 ;; -h | --help ) usage exit ;; esac; shift; done if [[ "$1" == '--' ]]; then shift; fi if [[ ${debug} -eq 1 ]]; then about fi if [[ ${#port[@]} -gt 0 ]]; then printf "PORT TO OPEN: %s\n" ${port[@]} fi if [[ ${override} -eq 0 && -r ${cacheFile} ]]; then while IFS= read -r line; do port[$idx]=$line idx=$(($idx+1)) done < ${cacheFile} fi for i in "${port[@]}"; do parsePort $i if [[ ${killFlag} -eq 1 ]]; then killTunnel else openTunnel fi done printf "%s\\n" "${port[@]}" > ${cacheFile} if [[ ${debug} -eq 1 ]]; then ps aux | grep "ssh -i ${privateKeyLoc}" | grep -v grep fi