A port rotator for mosh

Mosh is a great tool if you use SSH over unreliable connections.

By default it chooses a port within a pre-set range. You can also configure it to use a fixed port.

What you can’t (yet) do is get it to choose a port within a chosen range. This makes it tricky to open multiple terminals with if you are not using the pre-set range. It forces you to remember what terminals might already be open. The below script fixes that – it rotates through the range you configure.

#!/bin/bash

# Call this script instead of calling “mosh”, with all the parameters you would normally use, except –port. This script will choose the least-recently used port in the range you configure below.

# Script by: David Anderson – https://david.dw-perspective.org.uk
# Licence: Public domain

# Configuration: add your port range here
PORT_BOTTOM=60000
PORT_TOP=61000

if [[ -f ~/.moshport ]]; then
LASTPORT=`cat ~/.moshport`
[[ ! $LASTPORT -ge $PORT_BOTTOM || ! $LASTPORT -le $PORT_TOP ]] && LASTPORT=$PORT_TOP
else
LASTPORT=$PORT_TOP
fi

THISPORT=$((LASTPORT+1))
[[ $LASTPORT -ge $PORT_TOP ]] && THISPORT=$PORT_BOTTOM

echo “Calling mosh: –port=$THISPORT” “$@”

echo $THISPORT >~/.moshport

mosh –port=$THISPORT “$@”

Print This Page Print This Page
Tags: , , ,

Leave a Reply