10

My question is similar to this one, but I'm looking for something slightly different. I have a notebook PC that I use to access Linux machines on a network in two different scenarios:

  • I have a direct, wired connection to the network.

  • I have an indirect connection to the network. There is a gateway machine on the network exposed to the Internet, which I can use to establish SSH tunnels to hosts on the network. This is obviously a much slower, higher-latency connection.

My home directory is network-accessible from all machines, so they share a copy of my .bashrc. I would like to add functionality to .bashrc to detect which of the two scenarios I'm in and act accordingly (technically, there would be three scenarios, where the third is that I'm logging into my local machine, but that should be easily handled). I would like to do things like:

  • alias ssh ssh -X when I'm on the local network, but I don't want to use X forwarding over the Internet.

  • export EDITOR=gvim when I'm on the local network, but export EDITOR=vim when I'm remote.

And so on. Based on the previous answer, it looks like I should be able to accomplish something like this by checking the contents of SSH_CLIENT (if it exists) and seeing if the client IP address matches one of the network adapters on my local machine. I thought I would see if there is a slicker or more robust way to accomplish this.

Jason R
  • 645

1 Answers1

10

To detect an SSH session, use $SSH_CLIENT.

To distinguish between local and remote sessions, there are two possible approaches: client-side or server-side. On the server side, compare $SSH_CLIENT with the local IP address or routing table; this'll usually tell you whether the connection is from the LAN. On the client side, you may want to put ForwardX11 settings in your ~/.ssh/config: set it to yes for LAN hosts and to no for WAN hosts. This implies having a different ~/.ssh/config on different sites; that's what I do, and I generate mine with a shell script.

If X11 forwarding is on for LAN connections and off for WAN connections, then you can set your favorite editor to take $DISPLAY into account.

The server-side settings would normally go into your .profile (or .bash_profile if your login shell is bash and you use .bash_profile, or .zprofile if your login shell is zsh).

case ${SSH_CLIENT%% *}//$(/sbin/ifconfig |
                          sed -n 's/^.* addr:\([0-9][0-9.]*\) .*/\1/p' |
                          tr '\n' /)/ in
  "") :;;# local session
  10.42.*/10.42.*) :;; # LAN session
  1.2.3.*/1.2.3.*) :;; # LAN session
  *) unset DISPLAY;; # WAN session
esac
export EDITOR=vim
if [ -n "$DISPLAY" ] && type gvim >/dev/null 2>/dev/null; then
  EDITOR=gvim
fi
export VISUAL="$EDITOR"
  • on for LAN and off for LAN? The second should read WAN - but that`s a single character edit... – Nils Jan 18 '12 at 20:29