Simplifying host identification with rainbow terminals
In my daily work, I end up having to ssh
into a variety of hosts. Keeping track of which terminal is on which host can become challenging when I have 3 or 4 terminals all at a mysql
prompt, or tailing log files. A co-worker of mine came up with a pretty clever solution that I wanted to share. The clever solution involves some bash, and Applescript (as we’re working off of OSX). By aliasing ssh
to a custom script, we can modify the terminal background colour. Having colour-coded terminals makes it really easy to figure out which host you’re working on.
The bash script that powers the automatic colour changing behaviour looks like:
- #!/bin/bash
- #
- if [ "$2" ]; then
- exec ssh $*
- fi
- hostspec=$1
- host=$(echo $hostspec | sed -e 's/^.*@//' -e 's/\..*$//')
- # The default color which is pale yellow (solarized)
- # rgb(253,246,227) * 257 to get 16bit color values.
- default_color="65021, 63222, 58339"
- case "$host" in
- #
- # Add specific host cases here:
- #
- prod) host_color="12000, 2000, 12000";;
- staging) host_color="5000, 5000, 11808";;
- devimage) host_color="8000, 8000, 12000";;
- #
- #######
- *) # Compute default color based on first three letters of hostname
- declare -a cols
- host_color=$(perl -e '
- $DARKNESS = 4;
- $host = $ARGV[0];
- while ($host =~ /(.)/g) { $seed += ord($1) };
- srand($seed);
- for (1..3) {
- $c = int(rand() * 65535);
- if ($c > (65535/$DARKNESS)) {
- $c = $c / $DARKNESS
- }
- push @colors, $c;
- };
- print join (", ", @colors);
- ' $host)
- ;;
- esac
- window_name="${host}_SSH_$$"
- function set_color() {
- case "$TERM_PROGRAM" in
- iTerm.app)
- osascript <<EOF
- tell application "iTerm2"
- tell current window
- tell current session
- set background color to {$1}
- end tell
- end tell
- end tell
- EOF
- ;;
- esac
- }
- set_color "$host_color"
- LOCAL_TERMCOLOR="$host_color" ssh -o SendEnv=LOCAL_TERMCOLOR $hostspec
- set_color "$default_color"
I install this script as part of my dotfiles but you could put it in /usr/local/bin/colorssh
. Then in your bash profile, you can include alias ssh=/usr/local/bin/colorssh
. After reloading your bash environment, you should see your terminal background change colours each time you ssh into a machine. While the script ensures each host has the same colour all the time, if you’re not happy with a colour, you can always override it with a specific case. For example, I make my ‘prod’ hostname a lovely purple with:
- prod) host_color="12000, 2000, 12000";;
If the colour values look a bit alien, its because iTerm2 and Terminal.app want 16bit colour values. An easy way to get those values is to take your standard RGB values and multiply each value by 257
.
There are no comments, be the first!