Skip to content

Instantly share code, notes, and snippets.

@bneils
Last active February 10, 2023 18:47
Show Gist options
  • Save bneils/7fb8bceaf13e897ea339bdab38852326 to your computer and use it in GitHub Desktop.
Save bneils/7fb8bceaf13e897ea339bdab38852326 to your computer and use it in GitHub Desktop.
Connecting to a variable-IP SSH host on a set port.
#!/bin/bash
PORT=58309
USER=ben
MOUNT_DIR=/mnt/plex
IDENTITY_FILE=~/.ssh/id_rsa_plex
CACHE_FILE=/tmp/optiplex-temp-ip.cache
IPS=$(cat $HOME/optiplex_ips)
TIMEOUT=1
scan() {
output=$(timeout $TIMEOUT nc $1 $PORT | tr -d "\r")
filtered=$(echo $output | grep -i "ssh")
if [ "$filtered" != "" ] ; then
echo $1
fi
}
if [ "$1" == "-h" ] || [ "$1" == "--help" ] ; then
echo "usage: $0 [-h/--help] [-c/--clean] [-t/--tunnel] [-f/--fs]"
echo " -h, --help prints this message."
echo " -t, --tunnel creates a tunnel to the web client."
echo " -c, --clean removes the cache file."
echo " -f, --fs mounts the home file system at /mnt/plex."
exit
fi
if [ "$1" == "-c" ] || [ "$1" == "--clean" ] ; then
if [ -f "$CACHE_FILE" ] ; then
rm $CACHE_FILE
echo Removed cache file.
else
echo No cache file. Doing nothing.
fi
exit
fi
if [ -f "$CACHE_FILE" ] ; then
echo Ip already exists in cache.
else
# Concurrent scans
{
for ip in $IPS ; do
scan $ip &
done
} > $CACHE_FILE
echo Scanning... Wait no longer than $TIMEOUT seconds.
wait
ips=$(cat $CACHE_FILE)
num_ips=$(echo $ips | wc -w)
if [ "$num_ips" -ne 1 ] ; then
echo More than one, or no service was found!
echo IPs: $ips
rm $CACHE_FILE
exit 1
fi
echo Found that $ips:$PORT was running SSH
fi
if [ "$1" == "-t" ] || [ "$1" == "--tunnel" ] ; then
echo Tunneling localhost:8123 to destination:8080
LISTEN_ARGS="-L 8123:localhost:8080 -N"
else
LISTEN_ARGS=
fi
ip=$(cat $CACHE_FILE)
if [ "$1" == "-f" ] || [ "$1" == "--fs" ] ; then
mkdir -p $MOUNT_DIR
sudo sshfs -o allow_other,IdentityFile=$IDENTITY_FILE,StrictHostKeyChecking=no $USER@$ip:/home/$USER -p $PORT $MOUNT_DIR
echo Mounted at $MOUNT_DIR
exit 0
fi
echo ssh -X -i $IDENTITY_FILE $USER@$ip -p $PORT $LISTEN_ARGS
# StrictHostKeyChecking is disabled since the ip will vary a lot
ssh -X -i $IDENTITY_FILE $USER@$ip -p $PORT $ARGS $LISTEN_ARGS -o StrictHostKeyChecking=no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment