mosh NAT Script

In the past I required a custom script to mosh into my desktop, I was updating the script I use for this last night when I discovered it was no longer needed. I figured I might as well post the script here in case it helps someone else.

#!/bin/sh

# ########################################################## #
# wrapper for mosh to work with ssh's proxycommand directive #
# this only makes sense if the machine is directly reachable #
# from the internet using udp.                               #
# ########################################################## #

THISSCRIPT="`basename \"$0\"`"
REMOTE="$1"
REMOTEIP="$2"
NUM=`od -An -N1 -i /dev/random`
PORT=$((60000+NUM))

debug() {
    echo "[$THISSCRIPT] $@" >&2
}

usage() {
    debug "use me like this: $THISSCRIPT host [ip]"
}


# some default values
if [ -z "$REMOTEIP" ]; then
    if [ -z "$REMOTE" ]; then
        usage
        exit 1
    fi
    # does the remote have a hostname listed in .ssh/config
    REMOTEHOST="`grep -E -C1 \"^Host ([a-zA-Z0-9 ]+ )?$REMOTE( [a-zA-Z0-9 ]+)?$\" ~/.ssh/config | tail -n1 | gsed -r 's/\W*Hostname\W+//'`"
    if [ -z "$REMOTEHOST" ]; then REMOTEHOST="$REMOTE"; fi
    # resolve hostname
    REMOTEIP=`host -4 -t a $REMOTEHOST | head -n 1 | awk '{print $4}'`
    if [ -z "$REMOTEIP" ]; then
        debug "could not resolve hostname $REMOTE"
        exit 1
    fi
fi

debug "starting mosh-server on remote server $REMOTE $REMOTEIP:$PORT"
MOSHDATA="`ssh -t \"$REMOTE\" mosh-server new -i $REMOTEIP -p $PORT | grep '^MOSH' | tr -d \"\r\n\"`"
if [ -z "$MOSHDATA" ]; then
    debug "mosh-server could not be started"
    exit 1
fi

PORT="`echo -n \"$MOSHDATA\" | awk '{print \$4}'`"
MKEY="`echo -n \"$MOSHDATA\" | awk '{print \$5}'`"

if [ -z "$PORT" -o -z "$MKEY" ]; then
    debug "got no parseable answer"
    exit 1
fi

debug "starting local mosh-client to $REMOTEIP $PORT" 
MOSH_KEY="$MKEY" exec mosh-client "$REMOTEIP" "$PORT"

Reading: Crooked Little Vein

Aberdeen, Scotland: 12°C, Mostly cloudy throughout the day.