#!/bin/bash # # Simple $AUTOSSH and terminal multiplexer wrapper. # # Parameters # # We're enforcing a random monitoring por for autossh # as some systems might deny reading /proc/net/tcp like # kernels with grsecurity patch. BASENAME="`basename $0`" DEST="$1" COMMAND="$2" #LOCAL_MULTIPLEXER="wscreen" LOCAL_MULTIPLEXER="wtmux" MONITORING="-M $(($RANDOM + 1024))" AUTOSSH="autossh $MONITORING" # Set window title # http://stackoverflow.com/questions/899609/gnu-screen-run-script-that-sends-commands-to-the-screen-session-it-is-being-run function window_title { if [ -n "$STY" ]; then screen -p $WINDOW -X title "$*" elif [ -n "$TMUX" ]; then tmux rename-window "$*" else if which xtitle &> /dev/null; then xtitle -q "$*" fi fi } # Check if a named session exists, screen version function shell_wscreen_ls { screen -ls $1 | grep -q "There is a screen on" } # Check if a named session exists, tmux version function shell_wtmux_ls { tmux ls 2> /dev/null | grep -q ^$1: } # Try tmux, then screen function shell_remote_multiplexer { tmux="tmux attach" if [ ! -z "$1" ]; then tmux="$tmux -t $1" fi echo "$SUDO $tmux || $SUDO screen -x $1" } # Syntax check if [ -z "$DEST" ]; then exit 1 fi # Set default screen title window_title $DEST # Shift args if [ -z "$COMMAND" ]; then shift else shift 2 fi # Dispatcher if [ "$BASENAME" == "shells" ]; then # Remote screen shell using $AUTOSSH if [ "$COMMAND" == "root" ]; then SUDO="sudo" $AUTOSSH $DEST -t -- "`shell_remote_multiplexer`" else $AUTOSSH $DEST -t -- "`shell_remote_multiplexer` $COMMAND $*" fi else if [ -z "$COMMAND" ] && shell_${LOCAL_MULTIPLEXER}_ls $DEST; then # Local existing screen shell $LOCAL_MULTIPLEXER $DEST elif [ -z "$COMMAND" ] && [ "$DEST" == "root" ]; then # Local root shell window_title root SUDO="sudo" eval `shell_remote_multiplexer` elif [ -z "$COMMAND" ] && ( [ -f "$HOME/.screen/$DEST" ] || [ -f "$HOME/.tmux/$DEST" ] ); then # Local root shell window_title $DEST shell local $DEST $* elif [ "$DEST" == "local" ]; then # Local screen shell window_title $COMMAND $LOCAL_MULTIPLEXER $COMMAND $* else # Remote shell using $AUTOSSH $AUTOSSH $DEST -t -- $COMMAND $* fi fi # Restore screen title window_title terminal