Skip to content

Instantly share code, notes, and snippets.

@filippog
Created January 3, 2012 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filippog/1554170 to your computer and use it in GitHub Desktop.
Save filippog/1554170 to your computer and use it in GitHub Desktop.
automatic port detection for autossh
#!/bin/sh
# little wrapper to choose a random port for autossh
# falling back to $fallback_port
set -u
autossh_bin=${AUTOSSH_BIN:-/usr/local/bin/autossh.real}
fallback_port=${AUTOSSH_FALLBACK_PORT:-21021}
# XXX what if these are not available?
egrep=/usr/bin/egrep
lsof=/usr/sbin/lsof
od=/usr/bin/od
tr=/usr/bin/tr
# backwards compatibility, skip guess if -M is passed
echo "$@" | $egrep -q -- '-f?M ?[0-9]+'
if [ $? -eq 0 ] || [ -n "${AUTOSSH_PORT:-}" ]; then
exec $autossh_bin "$@"
fi
# take an int port and check whether it is in use (i.e. locally bound)
# unix command semantics: if in use return 0 else return 1
port_in_use() {
[ -z "$1" ] && return 0
$lsof -i tcp:$1 -s tcp:listen -Fp 1>/dev/null
free_all=$?
$lsof -i tcp@127.0.0.1:$1 -s tcp:listen -Fp 1>/dev/null
free_localhost=$?
[ $free_all -eq 0 ] || [ $free_localhost -eq 0 ]
return $?
}
portguess=""
if [ -r "/dev/urandom" ]; then
for t in $(seq 1 42); do
# get a random int for the tcp port
randport=$( $od -i -N2 -An /dev/urandom | $tr -d ' ' )
randport_1=$(( $randport + 1 ))
[ "$randport" -le 1024 ] && continue
[ "$randport" -ge 65535 ] && continue
# check if port is in use, race condition between here
# and the exec
if ! port_in_use $randport && ! port_in_use $randport_1; then
portguess=$randport
break
fi
done
fi
if [ -z "$portguess" ]; then
fallback=$fallpack_port
fallback_1=$(( $fallback_port + 1 ))
if ! port_in_use $fallback && ! port_in_use $fallback_1; then
portguess=$fallback_port
else
echo "unable to find a suitable tunnel port"
exit 1
fi
fi
export AUTOSSH_PORT="$portguess"
exec $autossh_bin "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment