Find the IP address of the client in an SSH session

LinuxNetworkingSshIp Address

Linux Problem Overview


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.

Linux Solutions


Solution 1 - Linux

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

Solution 2 - Linux

You could use the command:

server:~# pinky

that will give to you somehting like this:

Login      Name                 TTY    Idle   When                 Where 

root       root                 pts/0         2009-06-15 13:41     192.168.1.133

Solution 3 - Linux

Try the following to get just the IP address:

who am i|awk '{ print $5}'

Solution 4 - Linux

Just type the following command on your Linux machine:

who

Solution 5 - Linux

 who | cut -d"(" -f2 |cut -d")" -f1

Solution 6 - Linux

who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'


export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0

I use this to determine my DISPLAY variable for the session when logging in via ssh and need to display remote X.

Solution 7 - Linux

Improving on a prior answer. Gives ip address instead of hostname. --ips not available on OS X.

who am i --ips|awk '{print $5}' #ubuntu 14

more universal, change $5 to $6 for OS X 10.11:

WORKSTATION=`who -m|awk '{print $5}'|sed 's/[()]//g'`
WORKSTATION_IP=`dig +short $WORKSTATION`
if [[ -z "$WORKSTATION_IP" ]]; then WORKSTATION_IP="$WORKSTATION"; fi
echo $WORKSTATION_IP

Solution 8 - Linux

netstat -tapen | grep ssh | awk '{ print $4}'

Solution 9 - Linux

You can get it in a programmatic way via an SSH library (https://code.google.com/p/sshxcute)

public static String getIpAddress() throws TaskExecFailException{
	ConnBean cb = new ConnBean(host, username, password);
	SSHExec ssh = SSHExec.getInstance(cb);
	ssh.connect();
	CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
	String Result = ssh.exec(sampleTask).sysout;
	ssh.disconnect();	
	return Result;
}

Solution 10 - Linux

an older thread with a lot of answers, but none are quite what i was looking for, so i'm contributing mine:

sshpid=$$
sshloop=0
while [ "$sshloop" = "0" ]; do
        if [ "$(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT)" ];
then
                read sshClientIP sshClientSport sshClientDport <<< $(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT | cut -d= -f2)
                sshloop=1
        else
                sshpid=$(cat /proc/${sshpid}/status | grep PPid | awk '{print $2}')
                [ "$sshpid" = "0" ] && sshClientIP="localhost" && sshloop=1
        fi
done

this method is compatible with direct ssh, sudoed users, and screen sessions. it will trail up through the process tree until it finds a pid with the SSH_CLIENT variable, then record its IP as $sshClientIP. if it gets too far up the tree, it will record the IP as 'localhost' and leave the loop.

Solution 11 - Linux

A simple command to get a list of recent users logged in to the machine is last. This is ordered most recent first, so last | head -n 1 will show the last login. This may not be the currently logged in user though.

Sample output:

root     pts/0        192.168.243.99   Mon Jun  7 15:07   still logged in   
admin    pts/0        192.168.243.17   Mon Jun  7 15:06 - 15:07  (00:00)    
root     pts/0        192.168.243.99   Mon Jun  7 15:02 - 15:06  (00:03)    
root     pts/0        192.168.243.99   Mon Jun  7 15:01 - 15:02  (00:00)    
root     pts/0        192.168.243.99   Mon Jun  7 13:45 - 14:12  (00:27)    
root     pts/0        192.168.243.99   Mon May 31 11:20 - 12:35  (01:15)    
...

Solution 12 - Linux

I'm getting the following output from who -m --ips on Debian 10:

> root pts/0 Dec 4 06:45 123.123.123.123

Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.

Try this:

who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

Source:

Solution 13 - Linux

netstat -tapen | grep ssh | awk '{ print $10}'

Output:

two # in my experiment

netstat -tapen | grep ssh | awk '{ print $4}' 

gives the IP address.

Output:

127.0.0.1:22 # in my experiment

But the results are mixed with other users and stuff. It needs more work.

Solution 14 - Linux

Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).

Solution 15 - Linux

Usually there is a log entry in /var/log/messages (or similar, depending on your OS) which you could grep with the username.

Solution 16 - Linux

netstat will work (at the top something like this) tcp 0 0 10.x.xx.xx:ssh someipaddress.or.domainame:9379 ESTABLISHED

Solution 17 - Linux

Linux: who am i | awk '{print $5}' | sed 's/[()]//g'

AIX: who am i | awk '{print $6}' | sed 's/[()]//g'

Solution 18 - Linux

Search for SSH connections for "myusername" account;

Take first result string;

Take 5th column;

Split by ":" and return 1st part (port number don't needed, we want just IP):

netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":"); print a[1]}'


Another way:

who am i | awk '{l = length($5) - 2; print substr($5, 2, l)}'

Solution 19 - Linux

One thumb up for @Nikhil Katre's answer : >Simplest command to get the last 10 users logged in to the machine is last|head. > >To get all the users simply use last command

The one using who or pinky did what is basically asked. But But But they don't give historical sessions info.

Which might also be interesting if you want to know someone who has just logged in and logged out already when you start this checking.

if it is a multiuser system. I recommand add the user account you are looking for:

last | grep $USER | head

EDIT:

In my case, both $SSH_CLIENT and $SSH_CONNECTION do not exist.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflybywireView Question on Stackoverflow
Solution 1 - Linuxnolim1tView Answer on Stackoverflow
Solution 2 - LinuxvncpradoView Answer on Stackoverflow
Solution 3 - LinuxAlexPView Answer on Stackoverflow
Solution 4 - LinuxBangarView Answer on Stackoverflow
Solution 5 - LinuxdaniloView Answer on Stackoverflow
Solution 6 - LinuxSpindriftView Answer on Stackoverflow
Solution 7 - LinuxSeeBenClickView Answer on Stackoverflow
Solution 8 - LinuxSébastien MoreauView Answer on Stackoverflow
Solution 9 - Linuxvineetv2821993View Answer on Stackoverflow
Solution 10 - LinuxAndrejView Answer on Stackoverflow
Solution 11 - LinuxNikhil KatreView Answer on Stackoverflow
Solution 12 - LinuxmehovView Answer on Stackoverflow
Solution 13 - LinuxgerardView Answer on Stackoverflow
Solution 14 - LinuxmihiView Answer on Stackoverflow
Solution 15 - LinuxDaniel SchnellerView Answer on Stackoverflow
Solution 16 - LinuxaricView Answer on Stackoverflow
Solution 17 - LinuxpfrandsenView Answer on Stackoverflow
Solution 18 - LinuxNexView Answer on Stackoverflow
Solution 19 - LinuxKangqiao ZhaoView Answer on Stackoverflow