Skip to content

Instantly share code, notes, and snippets.

@cybic
Last active January 24, 2020 11:55
Show Gist options
  • Save cybic/7712be87530e1b8d02e1 to your computer and use it in GitHub Desktop.
Save cybic/7712be87530e1b8d02e1 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# AutoSSH to host and create or connect to tmux session
# Multi-hop version. Separate hops with `%`. Assign port with `:`
#
# $ remux-hop server.example.com sysop
# $ remux-hop alice.example.com%bob.example.com sysop
# $ remux-hop alice.example.com%[email protected]:2222 sysop
#
# Author: Oystein Steimler <[email protected]>
HLIST=$1;
IFS='%' read -a HOPS <<< "$HLIST"
AUTOSSHPRM="-M0 -o ServerAliveInterval=10 -o ServerAliveCountMax=2 -o BatchMode=yes"
SSHPRM="-A -t"
CMD="if tmux ls | grep ^$2; then tmux att -t $2; else tmux new -s $2;fi";
for ((i=${#HOPS[@]}-1; i>=1; i--))
do
PCMD=$(printf %q "$CMD");
## Separate host from port
IFS=':' read -a HOSTPARTS <<< "${HOPS[$i]}"
HOP=${HOSTPARTS[0]}
if [ -n "${HOSTPARTS[1]}" ]
then
echo "Setting port $PORT"
PORT="-p ${HOSTPARTS[1]} ";
fi
## Push a hop to the stack.
CMD="if [ \`which autossh\` ] ; then echo 'AutoSSH $HOP $PORT'; autossh $AUTOSSHPRM $SSHPRM $PORT $HOP $PCMD; else echo 'SSH $HOP $PORT'; ssh $SSHPRM $PORT $HOP $PCMD; fi ";
done
#echo $CMD;
#exit;
if [ `which autossh` ];
then
echo AutoSSH;
autossh $AUTOSSHPRM $SSHPRM ${HOPS[$i]} $CMD;
else
echo SSH;
ssh $SSHPRM ${HOPS[0]} $CMD;
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment