Search code examples
linuxsshnetwork-programmingip-address

Find the IP address of the client in an SSH session


I have a script that is to be run by a person that logs in to the server with SSH.

Is there a way to find out automatically what IP address the user is connecting from?

Of course, I could ask the user (it is a tool for programmers, so no problem with that), but it would be cooler if I just found out.


Solution

  • Check if there is an environment variable called:

    $SSH_CLIENT
    

    OR

    $SSH_CONNECTION
    

    (or any other environment variables) which gets set when the user logs in. Then process it using the user login script.

    Extract the IP:

    $ echo $SSH_CLIENT | awk '{ print $1}'
    1.2.3.4
    $ echo $SSH_CONNECTION | awk '{print $1}'
    1.2.3.4