Bash Script for detecting Server Change

37 views
Skip to first unread message

Snuffy2

unread,
May 14, 2021, 7:41:16 PM5/14/21
to tmate.io

There may be better ways to deal with this, but I've been using tmate to conncect to a few different SSH servers. I was getting frustrated about the regular change to the tmate server name that I decide dto write a bash script to detect and connect to the updated server name. Let me know if there are better ways to do this, but my script is below if it helps anyone.

Built for MacOS but should work in Linux as well with little to no modifications. Just update the myhost and user variables at the top.
--------------------------------
#!/bin/bash
while true; do
myhost=servername
user="tmate-username/session-name"

#####################################
scriptpath="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

default_svr="nyc1.tmate.io"
svr_file=${myhost}_server
error_file=${myhost}_error

if [ ! -f "${scriptpath}/${svr_file}" ]; then
    echo "Setting to default server: ${default_svr}"
    echo $default_svr > "${scriptpath}/${svr_file}"
fi

svr=$(cat "${scriptpath}/${svr_file}" | tr -d '\015')
#echo "ssh $user@$svr"
ssh $user@$svr
retVal=$?
if [ $retVal -eq 1 ]
then
    #echo "Exit Code: $retVal"
    echo
    ssh $user@$svr > "${scriptpath}/${error_file}" 2>&1
    new_svr=$(sed -n '/^The session has moved to another server./p;q' "${scriptpath}/${error_file}")
    if [[ ! -z "$new_svr" ]]
    then
        echo "Looking for new server"
        sed -n '3 s/.*@\(.*\)/\1/p' "${scriptpath}/${error_file}" > "${scriptpath}/${svr_file}"
        svr=$(cat "${scriptpath}/${svr_file}" | tr -d '\015')
        echo "New Server: ${svr}"
        read -t5 -n1 -rsp "Press any key to continue..."
        echo
    else
        read -t5 -n1 -rsp "Press any key to continue..."
        echo
        exit 1
    fi
else
    rm -f "${scriptpath}/${error_file}"
    clear
    exit 0
fi
done

Reply all
Reply to author
Forward
0 new messages