Ssh – How to automatically change terminal background, based on ssh hostname

gnome-terminalsshterminalwallpaper

How can one progmatically change the background colour of a terminal window, based on the hostname you ssh into?

i.e When I am ssh'd into live embedded systems on production hardware, I wish the terminal background to change to red – to "maintain awareness" of which server I am on. Having just the hostname in PS1 is not always sufficient.

Am using gnome-terminal, but would accept any workable solution under Linux.

Best Answer

You can use the ssh LocalCommand to emit the ANSI escape sequence to change background color, and have a section per host (or host pattern) to select the appropriate color you want to correspond to the remote host.

If your production servers follow a naming convention like "starts with prod", you can try the following snippet in your ~/.ssh/config file: Host prod* PermitLocalCommand yes LocalCommand printf "\x1b[41m\x1b[2JPRODUCTION SYSTEM [%n]\n\n"

If there isn't a handy naming convention to make use of wildcard patterns, you could just list the hostnames separated by spaces. You can create additional Host blocks with different color values and strings for various other non-production servers as well.

After connecting to a host that matches the pattern, the corresponding printf will be executed locally, changing the background color to red (the [41m chooses red as the background color, the [2J part repaints the entire screen with the updated background color. See https://en.wikipedia.org/wiki/ANSI_escape_code for lots more options)

The biggest nuisance about this approach is that the background color persists on exit from the ssh session; There is no counterpart to LocalCommand to be run on disconnect (that I am aware of). An alias or shell wrapper script for ssh could invoke printf "\x1b[0m" as a reset. On the other hand, having the background color set via LocalCommand means that you will get the color set even if ssh is not run via a wrapper script or alias.

Related Question