#!/bin/sh base_dir="$HOME/.rapid-tunneling" if [ "$1" = "--help" ]; then echo "Usage: $0 [-p] [-r] [-s] []" 1>&2 echo " -p: Print only pid of SSH process (if connecting or connected)." 1>&2 echo " Otherwise, print status" 1>&2 echo " Exit code: 0 if connected, 1 if connecting, 2 if not connected." 1>&2 echo " -s: Stop the tunnel" 1>&2 echo " -r: Remove the SSH keys (if not connected)" 1>&2 exit 255 fi remove=0 showpid=0 stop=0 if [ "$1" = "-p" ]; then showpid=1 shift elif [ "$1" = "-r" ]; then remove=1 shift elif [ "$1" = "-s" ]; then stop=1 shift fi pidfile="$1" [ -z "$pidfile" ] && pidfile="$base_dir/pid" connected() { [ "$showpid" = 1 ] && echo $pid || echo "Connected" exit 0 } connecting() { [ "$showpid" = 1 ] && echo $pid || echo "Connecting" exit 1 } not_connected() { [ "$showpid" = 1 ] || echo "Not connected" if [ "$remove" = 1 ]; then remove_ssh_keys exit 0 fi exit 2 } stop_it() { kill $pid 2>/dev/null remove_ssh_keys exit 0 } remove_ssh_keys() { sed -i '/ rapid-tunneling$/d' "$HOME/.ssh/authorized_keys" } pid=`cat "$pidfile" 2>/dev/null` [ "$pid" ] || not_connected kill -s 0 $pid 2>/dev/null || not_connected for i in /proc/$pid/fd/*; do socket=`readlink $i 2>/dev/null | sed -n 's/^socket:\[\(.*\)\]$/\1/p'` [ "$socket" ] || continue state=`awk '$10 == '"$socket"' {print $4}' /proc/net/tcp` [ "$state" ] || continue [ "$stop" = 1 ] && stop_it # A bug in sudo of centos5: does not FD for the listening socket: [ "$state" = "0A" ] && continue # "listening" [ "$state" = "01" ] && connected || connecting done not_connected