ScreenSSH
From Mike Neir's Wiki
Contents |
[edit]
Premise
I set these bash scripts up for use on my workstation at work. I'm constantly SSHing to servers, and find that it's quite beneficial to leave screens open with SSH sessions in them. These bash functions help to automate the process.
[edit]
Function: ssh
- The 'ssh' function overloads the ssh command, so running ssh from a command line will call the function instead of running the binary.
- The function tries to check to see if you're SSHing to an IP address, and if so, it will do a reverse lookup on the IP to see if it can get a hostname to use in naming the screen. If it fails, the IP address is used to name the screen.
- When making an SSH connection, the function will look for an unattached screen named after the host you're connecting to. If one exists, it will attach it. If none exist, it will make a new screen session.
function ssh
{
OLD_PROMPTCOMMAND=$PROMPT_COMMAND
DEST=`echo $1 | cut -d @ -f 2`
if [[ "$DEST" =~ "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" ]];
then
FINALDEST=`host $DEST | cut -d " " -f 5`
if [ "$FINALDEST" == "3(NXDOMAIN)" ] ;
then
FINALDEST=$DEST;
fi
else
FINALDEST=$DEST
fi
DETACHED=`screen -list | grep Detach | awk '{print $1}' | \
egrep $FINALDEST$| head -n 1`
#echo "DETACHED=$DETACHED";
if [[ "$DETACHED" =~ "^[0-9]{1,5}\.$FINALDEST$" ]];
then
#echo "we already have a terminal open! connect!"
/usr/bin/screen -r $DETACHED
else
#echo "nothing open, new connection"
/usr/bin/screen -S "$FINALDEST" -t "$FINALDEST" /usr/bin/ssh $*
fi
}
[edit]
Function: lsscr
- The lsscr function shows running screen sessions. It breaks them down into attached and detached sessions, and sorts them alphabetically by hostname.
- Searches can be performed by placing a search term as the first token after the lsscr command.
function lsscr
{
OLDIFS=$IFS
IFS=$'\n'
OUTPUT=`
for line in \`screen -list\`; do
if [[ "$line" =~ "([0-9]{1,5})\.(\S+)\s+\((\S+)\)" ]];
then
echo "${BASH_REMATCH[2]} ${BASH_REMATCH[1]} ${BASH_REMATCH[3]}";
fi
done;
`
AOUTPUT=`echo "$OUTPUT" | grep Attached | sort`
DOUTPUT=`echo "$OUTPUT" | grep Detached | sort`
if [ "$#" != "0" ];
then
AOUTPUT=`echo "$OUTPUT" | grep Attached | sort | grep $1`
DOUTPUT=`echo "$OUTPUT" | grep Detached | sort | grep $1`
else
AOUTPUT=`echo "$OUTPUT" | grep Attached | sort`
DOUTPUT=`echo "$OUTPUT" | grep Detached | sort`
fi
if [ "$DOUTPUT" != "" ];
then
echo "Detached Screens:"
echo "$DOUTPUT" | awk '{printf "%7s.%s\n", $2, $1}'
fi
if [ "$AOUTPUT" != "" ];
then
echo "Attached Screens:"
echo "$AOUTPUT" | awk '{printf "%7s.%s\n", $2, $1}'
fi
IFS=$OLDIFS
unset OLDIFS
unset OUTPUT
unset AOUTPUT
unset DOUTPUT
}
[edit]
Helpful Aliases
alias scrr='screen -r' alias SSH='/usr/bin/ssh'
