#!/bin/sh # check which IP is reachable since the notebook can be # connected via either Ethernet or WiFi, or both; # adjust portforwarding (which must otherwise be # already set up correctly -- like not forgetting # -A INPUT -d $IP -p tcp -m tcp --dport $DPT -j ACCEPT # # try to ping an already existing portforward target; # if unreachable or none, try to ping/add another one # # (c) 2009 Michael Shigorin # use, modify, distribute, cronjob this freely PATH=/sbin:$PATH IP=EX.TER.NAL.IP # 123.45.67.8 IP_E=NOTE.BOOK.ETH.IP # 192.168.1.2 IP_W=NOTE.BOOK.WIFI.IP # 192.168.1.3 PORT=EXT_PORT # 12345 DPT=DEST_PORT # 22 COUNT=0 IFS=":" ipt() { iptables "$1" PREROUTING -t nat \ -d "$IP" -p tcp -m tcp \ --dport "$PORT" \ -j DNAT --to-destination "$2:$DPT" } remove() { ipt -D "$1"; } add() { ipt -A "$1"; } try() { ping -w1 "$1" >&/dev/null; } # is current one reachable? COUNT="`iptables -L PREROUTING -t nat -n \ | fgrep "dpt:$port" \ | ( while read header to dest rest; do try "$dest" && let COUNT=$COUNT+1 || remove "$dest" done; echo $COUNT )`" # any job left? [ "$COUNT" = 0 ] || exit for ip in "$IP_W" "$IP_E"; do try "$ip" && let COUNT=$COUNT+1 && add "$ip" && break done # any job still left? [ "$COUNT" = 0 ] || exit # safety net: add via wifi if nothing else currently possible add "$IP_W"