Linux – Finding IP or hostname of origin machine (ssh)

environment-variableshostnamelinuxsshssh-tunnel

I connect to a number of machines constantly, from different physical locations (and thus different physical machines). Most of this is done though ssh, sometimes a gateway machine or two is required (which I invoke via ProxyCommand in ~/.ssh/config). I'd like to know if there's a method to identify the IP or hostname of the machine that calls the initial connection (ie the machine I'm working on) at the remote end?

  • I don't want to send environment variables as some machines I don't have root to set PermitUserEnvironment.
  • The $SSH_CLIENT environment variable is useful for direct connections, but only lists the most recent gateway.

My current idea for a solution is to grab $SSH_CLIENT, ssh to it, find that machine's $SSH_CLIENT value and repeat until it doesn't exist; then grab the hostname and pull it back somehow.

Seems like a bit of a hack job though; does anyone have a better method?

I'm working in a bash shell mostly, but I'm also happy for any suggestions that don't use it too.

Best Answer

I have never tried, but I can think of something that may work: You do not let SSH start your login shell, but take matters in your own hands. You can tell SSH to run arbitrary commands. Instead of

ssh remote_host

you would run something along the lines of

ssh remote_host -t "
    . /etc/profile; 
    . /etc/bash.bashrc; 
    DAT_ORIGIN_HOST=$(ifconfig eth0|grep -Po 't addr:\K[\d.]+') /bin/bash -l -i"

What this does is, it gives SSH something else to do instead of launching a login shell. That something is a string, which will be run as command, remotely. We use this to launch a shell in a very special manner: we give it an environmental variable DAT_ORIGIN_HOST, which contains our ip on eth0 (you may need to change that).

The trick we perform is that we put the command to execute remotely in double qoutes ". The double quotes (at least in Bash) mean, that BEFORE THE STRING IS PASSED TO SSH, our shell scans it and performs expansions/replacements, where appropriate. This means our shell will evaluate the `$(ifconfig ...) part, to our current ip address and pass ssh a string which contains the definition for an environmental variable with our local ip address.

Once logged in to the remote machine, echo $DAT_ORIGIN_HOST should print your IP address.

To develop that call to SSH I shamelessly took from here for extracting the IP address and here for the -t and how to launch something interactive

Disclaimer: I am unsure about the -l and -i option to /bin/bash. Maybe you need to omit them.

Related Question