Technical Musings: OSX SSH Terminal Console Coloring, Redux

Friday, January 25, 2013

OSX SSH Terminal Console Coloring, Redux

UPDATE: http://technicalmusings.blogspot.com/2013/02/something-about-my-previous-take-on.html
I've come up with a much better, simpler recipe to color my OSX Terminal session depending on the host I'm ssh-ing into. First, take a function with some cool BASH-only splitting and arrays and add that I found a way to address the current session in Applescript. Then add a one line way to enable bash ssh auto-complete when using the function. Ensure you pass all args to SSH so you can tunnel, etc. Finish with another line to switch the colors back to some default when you disconnect. Add this to your .profile, and voila!

This function assumes a certain host naming scheme, and that you have a Terminal profile for each environment.  I just copied 'Basic', and changed the background colors.  If you can't parse your server names, you need a better naming scheme ;)

ash() {
    ARGS="$@"
    IFS=" "
    set -- $ARGS 
    ARGSARRAY=( $@ )
    HOST=${ARGSARRAY[0]}
    IFS="-"
    set -- ${HOST}
    MYARRAY=( $@ )
    SERVERTYPE=${MYARRAY[0]}
    ENVNAME=${MYARRAY[1]}
    if [ "${ENVNAME}" = "pro" ]; then
        if [ "${serverType}" = "p19" ]; then
            PROFILE="Basic Green"
        else
            PROFILE="Basic Black"
        fi
    elif [ "${ENVNAME}" = "qa" ]; then
       PROFILE="Basic Grey"
    elif [ "${ENVNAME}" = "stage" ]; then
        PROFILE="Man Page"
    elif [ "${ENVNAME}" = "shadow" ]; then
        PROFILE="Basic Blue"
    else
        PROFILE="Basic"
    fi 
    echo "tell app \"Terminal\" to set current settings of first window to settings set \"${PROFILE}\"" | osascript
    ssh "${ARGS}" 

    echo "tell app \"Terminal\" to set current settings of first window to settings set \"Basic\"" | osascript 
}
complete -o default -o nospace -F _ssh ash
 
so:
$ ash test-pro-wxy01.test.com
 
will ssh to test-pro-wxy01.test.com and set the background to black, and when I logout, the background will be set to white.

gist: https://gist.github.com/4638756

One limitation currently, is that the hostname must be the first argument.

Another slight disadvantage is that you have to type something other than 'ssh'.  You could rename the ssh binary to something else, and then name the function 'ssh'.   Don't just name the function 'ssh' w/out renaming the binary (try it and find out why!)

Ideas taken from everywhere, including: https://raw.github.com/c3w/ash/master/ash

No comments: