How to automatically change terminal background, based on ssh hostname?

5,749

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.

Share:
5,749

Related videos on Youtube

Mtl Dev
Author by

Mtl Dev

PFY Graduate

Updated on September 18, 2022

Comments

  • Mtl Dev
    Mtl Dev over 1 year

    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.

  • Mtl Dev
    Mtl Dev over 7 years
    Is it possible to do something similar, to the PS1 prompt variable on the SSH host perhaps?
  • PKapp
    PKapp over 7 years
    The reset could be caused by sequences in either your PS1 prompt variable, or if you have commands like ls aliased to ls --color=auto and it includes the reset sequence '<ESC>[0m'. To persist though that, you would probably need to setup different gnome-terminal profiles, and go the wrapper script route, selecting a profile name based on the hostname, and invoking gnome-terminal --profile=$PROFILE_NAME -e ssh $HOST &