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.
Just type the following command on your Linux machine:
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)}'
I use this to determine my DISPLAY variable for the session when logging in via ssh and need to display remote X.
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).