SSH – Set Local Terminal Colors to Match Remote Machine

colorssshterminal

I have a color scheme that I like for when I'm in a terminal, but I ssh into the machine I work on from multiple sources (locally, PuTTY, my netbook, etc.) and I want to maintain the same color scheme throughout. Is this possible?

I especially want it in PuTTY; it's difficult to change PuTTY colors.

Best Answer

Colors in terminals are determined in two steps:

  • the program running in the terminal tells the terminal to use a certain color number;
  • the terminal translates each color number into a color value.

Xterm has an escape sequence to change the color value associated with a color number. I don't remember whether PuTTY supports this sequence; I know Mintty does.

set_color_value () {
  printf "\\e]4;$1;$2\\a"
}
set_color_value 4 '#6495ed'  # set color 4 (blue) to CornflowerBlue

These settings won't survive a terminal reset. You can overcome this difficulty by appending the cursor configuration changing sequence to your terminal's reset string.

  • On a terminfo-based system using ncurses, save your terminal's terminfo settings to a file with infocmp >>~/etc/terminfo.txt. Edit the description to change the rs1 (basic reset) sequence, e.g. replace rs1=\Ec by rs1=\Ec\E]4;4;#6495ed\E\\. With some programs and settings, you may need to change the rs2 (full reset) as well. Then compile the terminfo description with tic ~/etc/terminfo.txt (this writes under the directory $TERMINFO, or ~/.terminfo if unset).
  • On a termcap-based system, grab the termcap settings from your termcap database (typically /etc/termcap). Change the is (basic reset) and rs (full reset) sequences to append your settings, e.g. :is=\Ec\Ec\E]4;4;#6495ed\E\\:. Set the TERMCAP environment variable to the edited value (beginning and ending with :).

Now you can put something like this in your ~/.profile:

if [ "$(ps -p $PPID -o comm=)" = sshd ] &&
   [ "$TERM" = "xterm" ]; then
  set_color_value … # set color scheme
  TERMCAP=…  # if necessary
fi
Related Question