Get current ssh session's originating IP without being superuser

24,886

Solution 1

Answer to 1 & 2:

The warning is from netstat, not from grep and its about the PID/Program name column of the netstat output:

$ netstat -tapen
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode       PID/Program name

Using sudo:

$ sudo netstat -tapen
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode       PID/Program name

The alert is self explanatory, you have to be root to view the process IDs and program names owned by other (all) users, otherwise you will only get the PID/names of programs owned by you although you will get the open socket listings for those processes.

The distinction is basically summed up by the following, from man netstat:

   PID/Program name
       Slash-separated pair of the process id (PID) and process name of
the process that owns the socket.  --program causes this column  to
be  included. You will also need superuser privileges to see this  
information on sockets you don't own. This identification information is  
not yet available for IPX sockets.

In you case, the program sshd is owned by root, so without using sudo all the socket info will appear in the output, not the program name and PID. As a result while using grep on the result of netstat -taepn you are getting the warning.

On the other hand if you use sudo, the PID/program name will appear in the netstat -taepn output and you can use grep to find the output.

The following will make you more clear (check the last column(PID/Program name)):

$ netstat -tapen
                                                        PID/Program name
tcp  0  0 0.0.0.0:22  0.0.0.0:* LISTEN  0   11088       -               

$sudo netstat -taepn
tcp  0  0 0.0.0.0:22  0.0.0.0:* LISTEN  0   11088       1002/sshd       

If you are running this from a client machine then you can just ignore it as the process in that case will be ssh (not sshd) and will be owned by you.

Answer to 3:

There are so many ways. I will add a few:

$ sudo netstat -taepn | grep "ssh" | tr -s ' ' | cut -d' ' -f4 | head -1
192.168.5.3:22

$ sudo netstat -taepn | grep -Po "\b(\d|\.)+:22(?= .*ssh)"
192.168.5.3:22

$ sudo netstat -taepn | sed -nr '/ssh/s/.* ([^:]+:22) .*/\1/p'
192.168.5.3:22

EDIT: Without sudo:

$ netstat -taepn 2>/dev/null | grep ":22 " | tr -s ' ' | cut -d' ' -f4 | head -1
192.168.5.3:22

$ netstat -taepn 2>/dev/null | grep -Po "\b(\d|\.)+:22\b"
192.168.5.3:22

$ netstat -taepn 2>/dev/null | sed -nr '/:22 /s/.* ([^:]+:22) .*/\1/p'
192.168.5.3:22

EDIT 2:

If you want to get the remote IP address connected to port 22 (ssh) of the server without using sudo, your best best would be to read the socket statistics via ss command and get the desired output from that.

$ ss -ant | grep -Po "(\d|\.)+:22\s+\K[^:]+"
192.168.6.4

$ ss -ant | sed -nr 's/.*([0-9]|\.)+:22 +([^:]+).*/\2/p'
192.168.6.4

$ ss -ant | grep -e "ESTAB" | grep ":22" | tr -s ' ' | cut -d' ' -f5 | cut -d':' -f1
192.168.6.4

We have run the above commands in the server and 192.168.6.4 is the IP address of the remote computer connected to the server via ssh on port 22.

Solution 2

You can use the SSH_CONNECTION and SSH_CLIENT variables:

$ echo $SSH_CONNECTION 
10.0.0.1 42276 10.0.0.2 22
$ echo $SSH_CLIENT    
10.0.0.1 42276 22
$ SSH_IP=${SSH_CONNECTION%% *}
$ echo $SSH_IP
10.0.0.1

From man 1 ssh:

 SSH_CONNECTION        Identifies the client and server ends of the
                       connection.  The variable contains four space-
                       separated values: client IP address, client port
                       number, server IP address, and server port number.

You can access each entry in SSH_CONNECTION more easily if you split it into a bash array:

ssh_details=($SSH_CONNECTION)

Then you can get each entry using its index:

$ echo $SSH_CONNECTION 
127.0.0.1 55719 127.0.0.1 22
$ ssh_details=($SSH_CONNECTION)
$ echo ${ssh_details[0]}
127.0.0.1
$ echo ${ssh_details[1]}
55719
$ printf "You are logging in from host IP %s from port # %d\n" ${ssh_details[0]} ${ssh_details[1]}
You are logging in from host IP 127.0.0.1 from port # 55719

For some reason, SSH_CLIENT is not documented in the English manpages.

Share:
24,886

Related videos on Youtube

Tfb9
Author by

Tfb9

Updated on September 18, 2022

Comments

  • Tfb9
    Tfb9 almost 2 years

    I am trying to find out the current ssh session's originating IP address. I found the following to be useful, but it requires sudo:

    $ sudo netstat -tapen | grep ssh | awk '{ print $5}' | sed '/0.0.0.0\|::/d'
    192.168.1.1:60119
    99.xxx.xxx.xxx:1213
    

    Is there a way to get the 99.xxx.xxx.xxx information without a call to sudo?

    (Answered! Question #1: How is it that piping to grep returns only the error?)

    Question #2: Are there workarounds for getting WAN information with netstat? or...

    Question #3: Are there better options for my goal?

    • Organic Marble
      Organic Marble about 9 years
      conky gets it with ${tcp_portmon 22 22 rip 0} if that is any help. I have conky set up to display the # of SSH connections and their ip addresses.
    • Eliah Kagan
      Eliah Kagan about 9 years
      Do you want to see information about all currently existing SSH sessions on the machine, or do you want to see information about just the SSH session that you are using to run the command?
  • Tfb9
    Tfb9 about 9 years
    My system appears to behave different than yours. 'netstat -tapen', without sudo, returns 20 lines worth of results (from a fresh terminal); I can see the information without being superuser. Only if I pipe to 'grep' do I get the error.
  • heemayl
    heemayl about 9 years
    Its about the PID/Program name column of the output..without sudo sshd program name will not appear there hence the warning..check my edits
  • Tfb9
    Tfb9 about 9 years
    Oh, I see - thanks. Totally missed the warning and concentrated on the results. It is now dawning on me that the message was a stderr (or whatever) output from netstat, and that grep results are null when calling netstat without sudo. That takes care of Question #1!
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy about 9 years
    Note, that the output has nothing at all to do with grep
  • heemayl
    heemayl about 9 years
    This is wrong..without sudo the program name sshd will not be printed..
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy about 9 years
    @heemayl look at my screenshot there. I have ssh connection open. cat /etc/shadow proves that at that moment i dont have sudo working, on next line I have netstat -tapen 2> /dev/null | grep ssh and it shows. So . . . I guess it does work, doesn't it ?
  • heemayl
    heemayl about 9 years
    Thats your ssh client, not ssh daemon..
  • heemayl
    heemayl about 9 years
    Check my edited answer..
  • Tfb9
    Tfb9 about 9 years
    If I log in to my server from the WAN side, none of your three suggestions work; they either return 0.0.0.0:22 or 192.168.1.1:22. I am expecting something out of my LAN, i.e. 99.xxx.xxx.xxx.
  • Tfb9
    Tfb9 about 9 years
    One gets interesting results from who am i | awk '{print $5}' | sed 's/[()]//g' but from WAN from a cable-serviced client, I get the network name, not the IP address.
  • heemayl
    heemayl about 9 years
    @Tfb9 then why have you taken the 4th field in your original example? your example is very misleading.. the 4th field is always the local address & the 5th is the foreign address.. now it depends on whether you are running from the server or client.. in your original example the 4th field has port 22 meaning you have run it in the server..my answer is totally based on that.. What do you want actually? make it very precise & clear..
  • Tfb9
    Tfb9 about 9 years
    Sorry for the confusion, my end goal is really to get the IP address of a WAN-side client and logging that information (or kickout the user, depending). You are right the fifth column is really what I am looking for, but now would like to get that information without sudo. I will make an edit.
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy about 9 years
    Sigh . . . true that. OK, I'll edit my answer . . . The user can still see it by port number though, right ?
  • heemayl
    heemayl about 9 years
    @Tfb9: Check my Edit 2
  • Tfb9
    Tfb9 about 9 years
    Can I please ask for a bit of your time explaining to me how I can print You are logging in from host IP 111.111.111.111 from port # 49999 out of echo $SSH_CONNECTION results...?
  • muru
    muru about 9 years
    @Tfb9 see update.
  • Tfb9
    Tfb9 about 9 years
    This is great - I was expecting to deal with a sed command of some sort and I have now learned about a new way to do arrays, and some other grouping mecanism I'll now have to look into. Thank you, really!
  • Tfb9
    Tfb9 about 9 years
    If I may, a comment to your update/example. I do not think there is any way that echo ${ssh_details[0]} answers verbatim, specifically, 127.0.0.1... I get a null string from a local terminal.
  • muru
    muru about 9 years
    @Tfb9 it may or may not be 127.0.0.1. My example was from ssh localhost. Obviously your own maybe something else.
  • Tfb9
    Tfb9 about 9 years
    You are right again. I am doing most things through VNC, still, which is a different behavior from a terminal-opening point of view, basically $SSH_CONNECTION is empty from a locally-initiated terminal.