6

When logging in via SSH, I'd like to know, during the execution of .bashrc, the name of the host that is connecting.

Ubuntu Server shows the prompt:

Last login: Fri Feb 14 11:34:55 2014 from somehost.local

...so this information is available somewhere.

How can I access it?

3 Answers 3

7

If you type:

who

You'll see information about the logged in users. Amongst other things, you can see the host they're logged from. For instance, right now my laptop returns this:

who -u
darent   tty6         2014-02-14 01:15 11:02       20339
darent   tty7         2014-02-14 23:15  antic      31827 (:0)
darent   pts/7        2014-02-14 23:14 00:46       30246 (helena.local)
darent   pts/1        2014-02-14 23:16   .          1466 (:0)
darent   pts/9        2014-02-14 23:19 00:25         302 (:0)

Where helena.local is the computer from which I'm connected trough ssh.

2
  • You could probably combine "who" with some kind of "grep" or "cut" so instead or showing you all this output, it returned only "hostname.local" but I'm not really sure how to do it. Maybe somebody can improve my answer. Glad it helped :) Feb 15, 2014 at 14:47
  • The tty command will output a string that can be used to match the second column in your answer. Feb 15, 2014 at 22:19
5

ssh sets the environment variable $SSH_CONNECTION to contain client IP address, client port number, server IP address, and server port number seperated by spaces.

You can use

echo ${SSH_CONNECTION%% *}

to get the client's IP address. To get the DNS name use something like host or dig -x:

host ${SSH_CONNECTION%% *}
0
0
Last login: Fri Feb 14 11:34:55 2014 from somehost.local

This line shows the host from the previous, not the current login.

The who-method works for me. Better: who -m

Note, the variable SSH_CONNECTION gets lost if you start a subprocess, e.g. by calling su.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .