How to change terminal colors when connecting to SSH hosts

Solution 1:

  • .bash_aliases:
    function ssh_alias() {
      ssh "$@";
      setterm -default -clear rest;
      # If `-clear rest` gives error `setterm: argument error: 'rest'`, try `-clear reset` instead 
    }
    
    alias ssh=ssh_alias
    
  • /etc/ssh/ssh_config:
    # Ensure this line exists:
      PermitLocalCommand yes
    
  • .ssh/config:
    Host your.production.host
      User root
      LocalCommand setterm -term linux -back red -fore white -clear rest
    

In Bash, you can now:

some command

# all in default colors:
  ssh your.production.host

# colors changed:
# ....

exit
# colors changed back! yeea!


Alternative to setterm:

If you are using gnome-terminal, or another xterm, and are frustrated by the limited color choices of setterm, and/or your setterm changes are being overridden by color codes in your command prompt [$PS1], instead of setterm you may wish to use xtermcontrol, as demonstrated in this answer.

  • For example, xtermcontrol --bg '#600' will make the terminal background a dark red, although you may need to install xtermcontrol before using it (e.g. sudo apt install xtermcontrol on Debian-based systems)

Solution 2:

(Read gaRex's response first)

setterm has changed the arguments in recent versions: (more info: man setterm)

  • .bash_aliases:
    function ssh_alias() {
      ssh $@;
      setterm --default --clear all;
    }
    
    alias ssh=ssh_alias
    
    You can still use --clear rest and reload .bash_aliases via exec bash

  • .ssh/config:
    Host myproject.pro
      HostName myproject.com
      User root
      IdentityFile ~/.ssh/myproject
      LocalCommand setterm --term linux --background white --foreground black --clear all
    

Solution 3:

I follow a similar approach to Enrico's, changing the background/foreground of the terminal, then connecting to the server, and changing back the original color when disconnecting from the servers, with no admin permission needed, only requiring a few lines added to .bash_aliases:

alias background_local='printf "\e]11;#333333\e\\"'
alias background_server='printf "\e]11;#336699\e\\"'
alias goto_server='background_server; ssh server ; background_local"
  • If you wish, you can mix and match, changing also the foreground color with the command:
    alias foreground_server='printf "\e]10;#fff2af\e\\"'
    

I assumed you have a working .ssh/config file, so ssh server connects to your server; for completeness, in .ssh/config you may want to have:

Host server
  HostName address.to.your.server
  User yourusername