#!/bin/bash scriptName=$(basename $0) version=0.1 idx=0 killFlag=0 endpoint="192.168.105.100" user="$USER" cacheFile=.tunLast privateKeyLoc="~/.ssh/id_ecdsa" override=0 debug=0 fromPort=0 toPort=0 function killTunnel { if [[ debug -eq 1 ]]; then printf "killTunnel %d\n" $toPort fi pkill -f "ssh -i ${privateKeyLoc} -fNL 0.0.0.0:$toPort:" iptables -D INPUT -p tcp --dport $toPort -j ACCEPT 2>/dev/null } function openTunnel { ssh -i ${privateKeyLoc} -fNL 0.0.0.0:$toPort:${endpoint}:$fromPort ${user}@localhost iptables -A INPUT -p tcp --dport $toPort -j ACCEPT 2>/dev/null } 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 " } 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 ;; -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 [[ ${#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 netstat -lnptu | grep ssh fi