Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
    
Nice. A three character answer :) Thanks. –  Drew Noakes Feb 14 at 23:15
    
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 :) –  darent Feb 15 at 14:47
    
The tty command will output a string that can be used to match the second column in your answer. –  Drew Noakes Feb 15 at 22:19

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%% *}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.